package com.zoweunion.mechanic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.FacilitatorPersonnelRelationDao;
import com.zoweunion.mechanic.dao.TSSsVehicleBrandDao;
import com.zoweunion.mechanic.dao.TSSsVehicleModelDao;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.entity.*;
import com.zoweunion.mechanic.service.TSSsVehicleBrandService;
import com.zoweunion.mechanic.service.TSSsVehicleModelService;
import com.zoweunion.mechanic.service.base.impl.VehicleDataServiceImpl;
import com.zoweunion.mechanic.util.DateUtil;
import com.zoweunion.mechanic.util.FunUtil;
import com.zoweunion.mechanic.util.Orgin;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.zoweunion.mechanic.service.app.impl.OrderServicelmpl.createYMD;
import static com.zoweunion.mechanic.service.app.impl.OrderServicelmpl.differentDays;


@Service("tSSsVehicleModelService")
public class TSSsVehicleModelServiceImpl extends ServiceImpl<TSSsVehicleModelDao, TSSsVehicleModelEntity> implements TSSsVehicleModelService {

    @Autowired
    private TSSsVehicleModelDao tSSsVehicleModelDao;
    @Autowired
    private TSSsVehicleBrandService brandService;
    @Autowired
    private TSSsVehicleBrandDao brandDao;
    @Autowired
    private VehicleDataServiceImpl dataService;
    @Autowired
    private FacilitatorPersonnelRelationDao relationDao;
    @Autowired
    private AddressGEOUtil addressGEOUtil;
    @Autowired
    private ToolCarDataMapper toolCarDataMapper;

    @Override
    public PageInfo queryPage(Map<String, Object> map) {
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(map.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<TSSsVehicleModelEntity> mapList = tSSsVehicleModelDao.queryPage(map);
        PageInfo<TSSsVehicleModelEntity> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public PageInfo tSSsVehicleModelListFor(Map<String, Object> params) {
        LambdaQueryWrapper<TSSsVehicleModelEntity> lambdaQuery =
                Wrappers.<TSSsVehicleModelEntity>lambdaQuery();
        lambdaQuery.like(true, TSSsVehicleModelEntity::getModelName,
                params.get("modelName").toString()).eq(true, TSSsVehicleModelEntity::getDeleteFlag, 0);
        if (!params.get("brandId").toString().isEmpty()) {
            lambdaQuery.and(i -> i.eq(true, TSSsVehicleModelEntity::getBrandId,
                    params.get("brandId").toString()));
        }
        if (!params.get("typeId").toString().isEmpty()) {
            List<TSSsVehicleBrandEntity> entities = brandDao.listByIds(params.get("typeId").toString());
            if (entities.size() != 0) {
                List<String> stringList = entities.stream().map(TSSsVehicleBrandEntity::getId).collect(Collectors.toList());
                lambdaQuery.in(TSSsVehicleModelEntity::getBrandId, stringList);
            } else {
                lambdaQuery.and(i -> i.eq(true, TSSsVehicleModelEntity::getId,
                        -1));
            }
        }
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<TSSsVehicleModelEntity> mapList = tSSsVehicleModelDao.selectList(lambdaQuery);
        PageInfo<TSSsVehicleModelEntity> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    public List<Map<String, Object>> test() {
        List<Map<String, Object>> maps = tSSsVehicleModelDao.selectCount1();
        for (Map<String, Object> item : maps) {
            NumberFormat df = NumberFormat.getNumberInstance();
            df.setMaximumFractionDigits(2);
            double vv = 0d;
            double vvv = 0d;
            String thingsId = item.get("things_id").toString();
            List<Map<String, Object>> maps1 = tSSsVehicleModelDao.selectCount2(thingsId);
            double fuel = maps1.stream().mapToDouble(i -> Orgin.getDouble(i, "fuel")).sum();
            vv = fuel / maps1.size() + vv;
            item.put("最高油耗", maps1.get(0).get("fuel"));
            item.put("当天工作小时", maps1.get(0).get("hour"));
            item.put("日期", maps1.get(0).get("sample_date"));
            String byDate =
                    dataService.selectTableByThingsIdByDate(Orgin.getString(maps1.get(0), "things_id"),
                            Orgin.getDate(maps1.get(0), "sample_date"));
            Map<String, Object> sampleDate = tSSsVehicleModelDao.selectAvg(Orgin.getString(maps1.get(0), "things_id"),
                    byDate + "_tb1", maps1.get(0).get("sample_date"));
            item.put("当天的平均转速", Orgin.getDoubleValue(sampleDate, "RotateSpeed"));
            item.put("当天平均负载率", Orgin.getDoubleValue(sampleDate, "FDJNJ"));
            item.put("油耗", df.format(vv));
            List<Map<String, Object>> maps2 = tSSsVehicleModelDao.selectCount3(thingsId);
            double hour = maps2.stream().mapToDouble(i -> Orgin.getDouble(i, "hour")).sum();
            vvv = hour / maps1.size() + vvv;
            item.put("工作小时", df.format(vvv));
            item.put("平均每天油耗", df.format(vv / vvv));
            item.put("机型", thingsId);
            item.remove("things_id");
        }
        return maps;
    }

    @Override
    public List<Map<String, Object>> testZt() {
        List<Map<String, Object>> maps = tSSsVehicleModelDao.selectThingsId();
        for (Map<String, Object> item : maps) {
            String thingsId = Orgin.getString(item, "things_id");
            Date sampleDate = Orgin.getDate(item, "sample_date");
            String byDate =
                    dataService.selectTableByThingsIdByDate(thingsId,
                            sampleDate);
            List<Map<String, Object>> maps1 = tSSsVehicleModelDao.selectRoo(byDate + "_tb1", thingsId,
                    sampleDate);
            //单台逻辑处理
            List<Map<String, Object>> mapList1 = new ArrayList<>();
            List<Map<String, Object>> mapList2 = new ArrayList<>();
            List<Map<String, Object>> mapList3 = new ArrayList<>();
            List<Map<String, Object>> mapList4 = new ArrayList<>();
            List<Map<String, Object>> mapList5 = new ArrayList<>();
            for (int i = 0, maps1Size = maps1.size(); i < maps1Size; i++) {
                Map<String, Object> stringMap = new HashMap<>();
                Map<String, Object> item1 = maps1.get(i);//第一条
                if (maps1.size() - 1 != i) {
                    Map<String, Object> item2 = maps1.get(i + 1);//第二条
                    double rotateSpeed1 = Orgin.getDoubleValue(item1, "RotateSpeed");
                    double engineTotalHours1 = Orgin.getDoubleValue(item1, "EngineTotalHours");
                    double TotalFuelAmount1 = Orgin.getDoubleValue(item1, "TotalFuelAmount");
                    double rotateSpeed2 = Orgin.getDoubleValue(item2, "RotateSpeed");
                    double engineTotalHours2 = Orgin.getDoubleValue(item2, "EngineTotalHours");
                    double TotalFuelAmount2 = Orgin.getDoubleValue(item2, "TotalFuelAmount");
                    stringMap.put("engineTotalHours", engineTotalHours2 - engineTotalHours1);
                    stringMap.put("totalFuelAmount", TotalFuelAmount2 - TotalFuelAmount1);
                    if (rotateSpeed1 < 1000 && rotateSpeed2 < 1000) {
                        mapList1.add(stringMap);
                    } else if (rotateSpeed1 < 1500 && rotateSpeed2 < 1500 &
                            rotateSpeed1 > 1000 && rotateSpeed2 > 1000) {
                        mapList2.add(stringMap);
                    } else if (rotateSpeed1 < 1700 && rotateSpeed2 < 1700 &
                            rotateSpeed1 > 1500 && rotateSpeed2 > 1500) {
                        mapList3.add(stringMap);
                    } else if (rotateSpeed1 < 2000 && rotateSpeed2 < 2000 &
                            rotateSpeed1 > 1700 && rotateSpeed2 > 1700) {
                        mapList4.add(stringMap);
                    } else if (rotateSpeed1 > 2000 && rotateSpeed2 > 2000) {
                        mapList5.add(stringMap);
                    }
                }
                long id = Orgin.getLongValue(item, "id");
                if (maps1.size() - 1 == i) {
                    if (mapList1.size() != 0) {
                        insert1(mapList1, 1, thingsId, sampleDate, id);
                    }
                    if (mapList2.size() != 0) {
                        insert1(mapList2, 2, thingsId, sampleDate, id);
                    }
                    if (mapList3.size() != 0) {
                        insert1(mapList3, 3, thingsId, sampleDate, id);
                    }
                    if (mapList4.size() != 0) {
                        insert1(mapList4, 4, thingsId, sampleDate, id);
                    }
                    if (mapList5.size() != 0) {
                        insert1(mapList5, 5, thingsId, sampleDate, id);
                    }

                }
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> workSumHead(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> mapList = tSSsVehicleModelDao.selectCarNew(params);
        //总设备数
        map.put("countSum", mapList.size());
        Map<String, Object> selectAverage = tSSsVehicleModelDao.selectAverage(params);
        map.putAll(selectAverage);//总油耗 总工时 平均油耗
        double workHourSum = Orgin.getDoubleValue(map, "workHourSum");
        NumberFormat df = NumberFormat.getNumberInstance();
        df.setMaximumFractionDigits(2);
        long selectDay = tSSsVehicleModelDao.selectDay(params);
        if (selectDay == 0) {
            map.put("averEveryDay", 0.0);
        } else {
            map.put("averEveryDay", df.format(workHourSum / selectDay));
        }

        //同行业平均油耗
        map.putAll(tSSsVehicleModelDao.selectAverageAll(params));
        return map;
    }

    @Override
    public List<Map<String, Object>> modelPercent(Map<String, Object> params) {
        List<Map<String, Object>> mapList = tSSsVehicleModelDao.modelPercent(params);
        long countSum = tSSsVehicleModelDao.selectCountSum(params);
        mapList.forEach(item -> {
            int modelSum = Orgin.getIntValue(item, "modelSum");
            DecimalFormat df = new DecimalFormat("0.00%");
            item.put("percent", df.format((double) modelSum / countSum));
        });

        if (Orgin.getString(params, "s_id").equals("b2ee155eed7845809b24e84e54f35060")) {
            params.put("s_id", "6bd970ddd3e44e0f8646f951453ce18e");
            long countSum1 = tSSsVehicleModelDao.selectCountSum(params);
            List<Map<String, Object>> mapArrayList = new ArrayList<>();
            mapArrayList.add(this.getMap("XG956N", "23.53%", 0.235d, countSum1));
            mapArrayList.add(this.getMap("XG958N", "19.00%", 0.19d, countSum1));
            mapArrayList.add(this.getMap("XG955H", "14.48%", 0.145d, countSum1));
            mapArrayList.add(this.getMap("XG951H", "8.14%", 0.081d, countSum1));
            mapArrayList.add(this.getMap("XG822EL", "7.69%", 0.077d, countSum1));
            mapArrayList.add(this.getMap("XG806", "4.98%", 0.05d, countSum1));
            mapArrayList.add(this.getMap("XG931H", "4.07%", 0.041d, countSum1));
            mapArrayList.add(this.getMap("XG932H", "3.62%", 0.036d, countSum1));
            mapArrayList.add(this.getMap("XG956H", "2.71%", 0.027d, countSum1));
            mapArrayList.add(this.getMap("XG808", "2.26%", 0.023d, countSum1));
            mapArrayList.add(this.getMap("XG821", "1.81%", 0.018d, countSum1));
            mapArrayList.add(this.getMap("XG815W", "1.81%", 0.018d, countSum1));
            mapArrayList.add(this.getMap("XG530-DT5", "1.36%", 0.014d, countSum1));
            mapArrayList.add(this.getMap("XG833EH", "1.36%", 0.014d, countSum1));
            mapArrayList.add(this.getMap("XG916L", "1.36%", 0.014d, countSum1));
            mapArrayList.add(this.getMap("XG962H", "0.90%", 0.009d, countSum1));
            mapArrayList.add(this.getMap("XG807W", "0.90%", 0.009d, countSum1));
            return mapArrayList;
        }
        return mapList;
    }

    private Map<String, Object> getMap(String modelName, String percent, Double modelSum, Long countSum) {
        Map<String, Object> map = new HashMap<>();
        map.put("modelName", modelName);

        map.put("percent", percent);
        map.put("modelSum", (int) (modelSum * countSum));
        return map;
    }

    ;

    /**
     * 故障排行
     */
    @Override
    public List<Map<String, Object>> spnOrder(Map<String, Object> params) {
        //type为1时，表示车主情况下，进行故障代码的统计，同时车主情况需要传参oId和type，但是服务商情况下不需要传参
        if (params.containsKey("type") && Orgin.getIntValue(params, "type") == 1) {
            return tSSsVehicleModelDao.spnOrderByOwner(params);
        } else {
            return tSSsVehicleModelDao.spnOrder(params);
        }
    }

    /**
     * 工时油耗统计
     */
    @Override
    public Map<String, Object> workFuel(Map<String, Object> params) {
        // 如果有cId把oId移除，查询单独一辆车
        if (params.containsKey("cId")) {

            if (!params.get("cId").toString().isEmpty()) {

                params.remove("oId");
                params.remove("s_id");
            }
        }
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("workHourSum", 0);
        hashMap.put("fuelSum", 0);
        hashMap.put("average", 0);
        // 计算总工时，总油耗，每小时油耗
        Map<String, Object> selectAverage = tSSsVehicleModelDao.selectAverage(params);
        if (selectAverage != null) {
            hashMap.putAll(selectAverage);
        }
        Date startTime = Orgin.getDate(params, "startTime");
        Date endTime = Orgin.getDate(params, "endTime");
        int type = Orgin.getIntValue(params, "type");
        List<Map<String, Object>> arrayList = new ArrayList<>();

//        type: 2 用type区分月和年
//        startTime: 2021-01-01
//        endTime: 2021-12-31
//        modelId: 车型id
//        provinceCode: 省份的id
        // type 1 是日
        if (type == 1) {
            List<String> ymd = createYMD(startTime, endTime);
            ymd.forEach(item -> {
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("fuelSum", 0);
                stringObjectHashMap.put("average", 0);
                stringObjectHashMap.put("workHourSum", 0);
                stringObjectHashMap.put("date", item);
                stringObjectHashMap.put("workHourAverage", 0);
                stringObjectHashMap.put("fuelAverage", 0);
//                params.put("ymd",item);
//                //进行总油耗和总工时的统计，如果是车主账号，就会传参oId，并且如果是车主选择车辆或者是具体车辆页面则会传参cId
//                Map<String, Object> stringObjectMap = tSSsVehicleModelDao.workFuel(params);
//                if(stringObjectMap!=null){
//                    stringObjectHashMap.putAll(stringObjectMap);
//                }
//                // 新增字段：isAllDayAveData 是否需要全国的当日/当月的平均数据，如果不需要可以不传字段或者传字段为false
//                if (params.containsKey("isAllDayAveData") && Orgin.getBoolean(params, "isAllDayAveData") == true) {
//                    Map<String, Object> allDayAveData = tSSsVehicleModelDao.allDayAveData(params);
//                    if(allDayAveData!=null){
//                        stringObjectHashMap.putAll(allDayAveData);
//                    }
//                }
                arrayList.add(stringObjectHashMap);
            });


            //进行总油耗和总工时的统计，如果是车主账号，就会传参oId，并且如果是车主选择车辆或者是具体车辆页面则会传参cId
            List<Map<String, Object>> stringObjectMap = tSSsVehicleModelDao.workFuelList(params);
            // 新增字段：isAllDayAveData 是否需要全国的当日/当月的平均数据，如果不需要可以不传字段或者传字段为false
            List<Map<String, Object>> allDayAveData = new ArrayList<>();
            if (params.containsKey("isAllDayAveData") && Orgin.getBoolean(params, "isAllDayAveData") == true) {
                allDayAveData = tSSsVehicleModelDao.allDayAveDataList(params);
            }
            List<Map<String, Object>> finalAllDayAveData = allDayAveData;
            arrayList.forEach(item1 -> {
                stringObjectMap.forEach(item2 -> {
                    if (item2.get("date").toString().equals(item1.get("date"))) {
                        item1.put("fuelSum", item2.get("fuelSum"));
                        item1.put("average", item2.get("average"));
                        item1.put("workHourSum", item2.get("workHourSum"));
                    }
                });
                if (params.containsKey("isAllDayAveData") && Orgin.getBoolean(params, "isAllDayAveData") == true) {
                    finalAllDayAveData.forEach(item3 -> {
                        if (item3.get("date").toString().equals(item1.get("date"))) {
                            item1.put("workHourAverage", item3.get("workHourAverage"));
                            item1.put("fuelAverage", item3.get("fuelAverage"));
                        }
                    });
                }
            });
        }
        // type 2 是月份的
        else if (type == 2) {
            LocalDate today = startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            for (long i = 0L; i <= 11L; i++) {
                LocalDate localDate = today.plusMonths(i);
                String item = localDate.toString().substring(0, 7);
                params.put("ymdS", item + "-01");
                params.put("ymdE", item + "-31");
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("fuelSum", 0);
                stringObjectHashMap.put("average", 0);
                stringObjectHashMap.put("workHourSum", 0);
                stringObjectHashMap.put("date", item);
                stringObjectHashMap.put("workHourAverage", 0);
                stringObjectHashMap.put("fuelAverage", 0);
                //如果是车主账号，就会传参oId，并且如果是车主选择车辆或者是具体车辆页面则会传参cId
                Map<String, Object> stringObjectMap = tSSsVehicleModelDao.workFuel(params);
                if (stringObjectMap != null) {
                    stringObjectHashMap.putAll(stringObjectMap);
                }
                // 新增字段：isAllDayAveData 是否需要全国的当日/当月的平均数据，如果不需要可以不传字段或者传字段为false
                if (params.containsKey("isAllDayAveData") && Orgin.getBooleanValue(params, "isAllDayAveData") == true) {
                    Map<String, Object> allDayAveData = tSSsVehicleModelDao.allDayAveData(params);
                    if (allDayAveData != null) {
                        stringObjectHashMap.putAll(allDayAveData);
                    }
                }
                arrayList.add(stringObjectHashMap);
            }
        }
        hashMap.put("datalist", arrayList);
        return hashMap;
    }


    @Override
    public List<Map<String, Object>> workByPro(Map<String, Object> params) {
        List<String> strings = tSSsVehicleModelDao.selectPro(params);
        List<Map<String, Object>> arrayList = new ArrayList<>();
        strings.forEach(item -> {
            params.put("item", item);
            Map<String, Object> stringObjectMap = new HashMap<>();
            stringObjectMap.put("workHourSum", 0.00);
            stringObjectMap = tSSsVehicleModelDao.selectByPro(params);
            if (stringObjectMap != null) {
                stringObjectMap.put("provinceCode", item);
                arrayList.add(stringObjectMap);
            }

        });
        return arrayList;
    }

    @Override
    public List<Map<String, Object>> modelList(Map<String, Object> params) {
        return tSSsVehicleModelDao.modelList(params);
    }

    @Override
    public List<Map<String, Object>> onlineCurrentList(Map<String, Object> params) {
        this.ifDemo(params);
        Date startDate = DateUtils.addDays(new Date(), -30);
        List<String> ymd = createYMD(startDate, new Date());
        List<Map<String, Object>> strings = new ArrayList<>();

        Map<String, Object> timeMap = new HashMap<>();

        timeMap.put("startTime", ymd.get(0));
        timeMap.put("endTime", ymd.get(ymd.size() - 1));

        List<Map<String, Object>> onlineList = tSSsVehicleModelDao.onlineCurrentList(params, timeMap);

        ymd.forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("date", item);
            map.put("count", '0');
            onlineList.forEach(onlineMap -> {

                if (onlineMap.get("date").equals(item)) {

                    map.put("count", onlineMap.get("count"));
                }
            });

            strings.add(map);
        });

        return strings;
    }

    @Override
    public List<Map<String, Object>> provinceList(Map<String, Object> params) {
        this.ifDemo(params);
        return tSSsVehicleModelDao.provinceList(params);
    }

    @Override
    public Map<String, Object> idlingPercent(Map<String, Object> params) {
        this.ifDemo(params);
        Map<String, Object> map = new HashMap<>();
        //总数
        List<Double> doubles = tSSsVehicleModelDao.selectIdlingPercent(params);
        //怠速
        List<Double> collect = doubles.stream().filter(x -> x < 1000d).collect(Collectors.toList());
        DecimalFormat df = new DecimalFormat("0.00");
        //怠速百分比
        String format = df.format((double) collect.size() * 100 / doubles.size());
        map.put("idlingPer", format + "%");
        //负荷百分比
        String format1 = df.format((1 - (double) collect.size() / doubles.size()) * 100);
        map.put("workPer", format1 + "%");
        return map;
    }

    @Override
    public Map<String, Object> faultListNew(Map<String, Object> params) {
        this.ifDemo(params);
        Map<String, Object> map = new HashMap<>();
        //最近五条
        map.put("list", tSSsVehicleModelDao.faultListNew(params));
        //今日报警数
        map.put("count", tSSsVehicleModelDao.faultListCount(params));
        return map;
    }

    @Override
    public List<Map<String, Object>> workingFuelNew(Map<String, Object> params) {
        this.ifDemo(params);
        Date startDate = DateUtils.addDays(new Date(), -30);
        List<String> ymd = createYMD(startDate, new Date());
        List<Map<String, Object>> strings = new ArrayList<>();
        ymd.forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("date", item);
            map.put("workHourSum", 0.00);
            map.put("fuelSum", 0.00);
            Map<String, Object> map1 = tSSsVehicleModelDao.selectFuelWorking(params, item);
            if (map1 != null) {
                map.putAll(map1);
            }
            strings.add(map);
        });
        return strings;
    }

    @Override
    public Map<String, Object> mapCount(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> maps = tSSsVehicleModelDao.selectCarNew(params);
        //设备总数量
        map.put("count", maps.size());
        map.put("carOnline", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 1).count());
        map.put("carIdling", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 1 &&
                        Orgin.getIntValue(o, "RotateSpeed") < 1000).count());
        map.put("carOffLine", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 2).count());
        map.put("faultCount", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "fault_status") == 1).count());
        return map;
    }

    @Override
    public Map<String, Object> mapListNew(Map<String, Object> map) {
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(map.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList = tSSsVehicleModelDao.mapListNew(map);
        mapList.forEach(item -> {
            String longitude = Orgin.getString(item, "GPSlongitude");
            String latitude = Orgin.getString(item, "GPSlatitude");
            String address = "";
            if (longitude != null && latitude != null) {
                address = addressGEOUtil.getAddress(longitude, latitude);
            }
            item.put("m_location", address);
            String workHoursJson = toolCarDataMapper.getWorkHoursToday(Orgin.getString(item, "things_id"));
            if (workHoursJson == null) {
                item.put("workHour", "0");
            } else {
                HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>() {
                });
                double workHours = Orgin.getDoubleValue(workHoursMap, "workHours");
                item.put("workHour", Math.floor(workHours) + "小时" + Math.floor(workHours % 1 * 60) + "分钟");
            }
            //获取设备列表
            List<Map<String, Object>> equipments = toolCarDataMapper.getEquipmentList(Orgin.getString(item, "car_id"));
            if(equipments.size() > 0){
                item.put("equipments", equipments);
            }
        });
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("data", mapPageInfo);
        Map<String, Object> map1 = new HashMap<>();
        List<Map<String, Object>> maps = tSSsVehicleModelDao.selectCarNew(map);
        // 设备总数量
        map1.put("count", maps.size());
        // status 1在线 2离线
        // fault_status 1: 有故障 2: 无故障
        // 在线且无故障归为在线
        /*map1.put("carOnline", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 1 &&
                        Orgin.getIntValue(o, "fault_status") == 2).count());*/
        //新的在线判断
        map1.put("carOnline", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "device_status") == 1).count());

        /*map1.put("carIdling", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 1 &&
                        Orgin.getIntValue(o, "RotateSpeed") < 1000).count());*/
        //新的怠速判断
        map1.put("carIdling", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "device_status") == 1 &&
                        Orgin.getIntValue(o, "RotateSpeed") < 1000).count());

        // 离线且无故障归为离线
        /*map1.put("carOffLine", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 2 &&
                        Orgin.getIntValue(o, "fault_status") == 2).count());*/

        //新的离线状态判断
        map1.put("carOffLine", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "device_status") == 2).count());
        //故障判断
        map1.put("faultCount", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "fault_status") == 1).count());

        // 工作状态判断
        map1.put("carWorkLine", maps.stream()
                .filter(o -> Orgin.getIntValue(o, "status") == 1).count());

        //绑定电子围栏的车辆数
        map1.put("bindEnclosureCount", maps.stream()
                .filter(o -> Orgin.getString(o, "e_id") != null).count());

        map2.put("dataCount", map1);
        return map2;
    }

    @Override
    public Map<String, Object> mapInfoNew(Map<String, Object> params) {
        Map<String, Object> item = tSSsVehicleModelDao.mapInfoNew(params);
        String longitude = Orgin.getString(item, "GPSlongitude");
        String latitude = Orgin.getString(item, "GPSlatitude");
        String address = addressGEOUtil.getAddress(longitude, latitude);
        item.put("m_location", address);
        return item;
    }

    private void insert1(List<Map<String, Object>> mapList1, Integer type
            , String thingsId, Date sampleDate, Long id) {
        double engineTotalHours = mapList1.stream().mapToDouble(x -> Orgin.getDoubleValue(x, "engineTotalHours")).sum();
        double totalFuelAmount = mapList1.stream().mapToDouble(x -> Orgin.getDoubleValue(x, "totalFuelAmount")).sum();
        tSSsVehicleModelDao.insertValue(engineTotalHours, totalFuelAmount, thingsId, sampleDate, type);
        //todo 更新状态
        tSSsVehicleModelDao.updateStatus(id);
    }

    public Map<String, Object> ifDemo(Map<String, Object> params) {
        params.put("demoType", 0);
        if (params.get("s_id") != null && Orgin.getString(params, "s_id").equals(Constants.DEMO_ACCOUNT_S_ID[0])) {
            params.put("demoType", 1);
        }
        return params;
    }

    @Override
    public PageInfo tSSsCarOwnerRang(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> carOwnerList = tSSsVehicleModelDao.getCarOwnerListForCarOwnerRang(params);
        PageInfo<Map<String, Object>> carOwnerRangMapListPageInfo = new PageInfo<>(carOwnerList);

        List<Map<String, Object>> carOwnerRangMapList = new ArrayList<>();
        List<Map<String, Object>> rangAll = tSSsVehicleModelDao.getRangForCarOwner(params);
        rangAll.forEach(rangItem -> {
            carOwnerList.forEach(carOwnerItem -> {
                if (rangItem.get("o_id").equals(carOwnerItem.get("o_id"))) {
                    carOwnerItem.put("rang", rangItem.get("rang"));
                    carOwnerRangMapList.add(carOwnerItem);
                    return;
                }
            });
        });
        carOwnerRangMapListPageInfo.setList(carOwnerRangMapList);
        return carOwnerRangMapListPageInfo;
    }

    /**
     * 这里可以查出排名的 o_id 然后再查出对应的信息
     * @param params
     * @return
     */
    @Override
    public PageInfo tSSsCarOwnerRang2(Map<String, Object> params) {

        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        // 查询车主排名信息
        // 这里需要算出每天的平均工作小时数
        List<Map<String, Object>> carOwnerList = tSSsVehicleModelDao.getCarOwnerListForCarOwnerRang(params);
        PageInfo<Map<String, Object>> carOwnerRangMapListPageInfo = new PageInfo<>(carOwnerList);

        List<Map<String, Object>> carOwnerRangMapList = new ArrayList<>();
        // 这里又查询了一遍,两个list对比 o_id 是否相等，这里计算出了排名
        List<Map<String, Object>> rangAll = tSSsVehicleModelDao.getRangForCarOwner(params);
        rangAll.forEach(rangItem -> {
            carOwnerList.forEach(carOwnerItem -> {
                if (rangItem.get("o_id").equals(carOwnerItem.get("o_id"))) {
                    carOwnerItem.put("rang", rangItem.get("rang"));
                    // 每天的平均时长
//                    float per_hour = 0;
//                    if(carOwnerItem.get("work_hours_total_all_car")!=null && carOwnerItem.get("work_hours_total_all_car")!=null){
//                        per_hour = (float) carOwnerItem.get("work_hours_total_all_car")/(float) carOwnerItem.get("work_hours_total_all_car");
//                    }
//                    carOwnerItem.put("per_hour", per_hour);
                    String perHour = "/";
                    if(carOwnerItem.get("per_hour") != null){
                        perHour = String.format("%.2f", carOwnerItem.get("per_hour"));
                    }
                    carOwnerItem.put("per_hour",perHour);
                    carOwnerRangMapList.add(carOwnerItem);
                    return;
                }
            });
        });
        carOwnerRangMapListPageInfo.setList(carOwnerRangMapList);
        return carOwnerRangMapListPageInfo;
    }

    @Override
    public List<Map<String, Object>> tSSsCarRang(Map<String, Object> params) {
        List<Map<String, Object>> carList = tSSsVehicleModelDao.getCarListForCarOwnerRang(params);

        List<Map<String, Object>> carRangMapList = new ArrayList<>();
        List<Map<String, Object>> rangAll = tSSsVehicleModelDao.getRangForCar(params);
        rangAll.forEach(rangItem -> {
            carList.forEach(carItem -> {
                if (rangItem.get("car_id").equals(carItem.get("car_id"))) {
                    carItem.put("rang", rangItem.get("rang"));

                    params.put("things_id", carItem.get("things_id"));
                    Map<String, Object> result = tSSsVehicleModelDao.query6mAvgDataForThings(params);
                    carItem.put("work_hours_recently_6mo_avg", result == null ? null : result.get("work_hours_recently_6mo_avg"));
                    carRangMapList.add(carItem);
                    return;
                }
            });
        });

        return carRangMapList;
    }

    @Override
    public List<CarOwnerRangDataBean> exportTSSsCarOwnerRangData(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        List<CarOwnerRangDataBean> list = new ArrayList<>();
        PageInfo pageInfo = this.tSSsCarOwnerRang2(params);
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;

            CarOwnerRangDataBean info = new CarOwnerRangDataBean();
            info.setRang(map.get("rang").toString());
            info.setUserName(map.get("user_name").toString());
            info.setMobilePhone(map.get("mobile_phone") == null ? "/" : map.get("mobile_phone").toString());
            info.setWorkHoursTotalAllCar(map.get("work_hours_total_all_car") == null ? "/" : String.format("%.2f", map.get("work_hours_total_all_car")));
            info.setPerHour(map.get("per_hour") == null ? "/": map.get("per_hour").toString());
            info.setRegionName(map.get("region_name") == null ? "/" : map.get("region_name").toString());
            list.add(info);
        });

        return list;
    }

    @Override
    public PageInfo tSSsCarOwnerForWorkPerRang(Map<String, Object> params) throws ParseException {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> carOwnerList = tSSsVehicleModelDao.getCarOwnerListForCarWorkPerRang(params);
        PageInfo<Map<String, Object>> carOwnerRangMapListPageInfo = new PageInfo<>(carOwnerList);

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endDate = ft.parse(params.get("endDate").toString());
        Date startDate = ft.parse(params.get("startDate").toString());

        // 查询在线数量
        carOwnerList.forEach(carOwnerMap -> {

            params.put("o_id", carOwnerMap.get("o_id").toString());

            Map<String, Object> carMap = (Map<String, Object>) carOwnerMap;

            // 查询车主名下的设备数量在线数
            List<Map<String, Object>> onlineCountList = tSSsVehicleModelDao.selectOwnerThingsOnlineCount(params);

            int onlineCount = Integer.valueOf(onlineCountList.get(0).get("onlineCount").toString());

            // 查询车主名下的设备数量
            int thingsCount = tSSsVehicleModelDao.selectOwnerThingsCount(params);

            if (onlineCount == 0) {

                carMap.put("car_work_per", "0");
            } else {
                carMap.put("car_work_per", String.format("%.4f", Double.valueOf(onlineCount) / Double.valueOf(thingsCount * differentDays(startDate, endDate))));
            }
        });
        List<Map<String, Object>> carOwnerRangMapList = new ArrayList<>();
        List<Map<String, Object>> rangAll = tSSsVehicleModelDao.getRangForCarWorkPerRang(params);
        rangAll.forEach(rangItem -> {
            carOwnerList.forEach(carOwnerItem -> {
                if (rangItem.get("o_id").equals(carOwnerItem.get("o_id"))) {
                    carOwnerItem.put("rang", rangItem.get("rang"));
                    carOwnerRangMapList.add(carOwnerItem);
                    return;
                }
            });
        });
        carOwnerRangMapListPageInfo.setList(carOwnerRangMapList);
        return carOwnerRangMapListPageInfo;
    }

    @Override
    public List<Map<String, Object>> tSSsCarRangForWorkPerRang(Map<String, Object> params) throws ParseException {
        List<Map<String, Object>> carList = tSSsVehicleModelDao.getCarListForCarWorkPerRang(params);

        params.put("thingsDate", true);

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endDate = ft.parse(params.get("endDate").toString());
        Date startDate = ft.parse(params.get("startDate").toString());

        List<Map<String, Object>> onlineCountList = tSSsVehicleModelDao.selectOwnerThingsOnlineCount(params);

        // 查询在线数量
        carList.forEach(carOwnerMap -> {

            String things_id = carOwnerMap.get("things_id").toString();

            carOwnerMap.put("car_work_per", "0");

            onlineCountList.forEach(onlineMap -> {

                String onlineThingsId = onlineMap.get("things_id").toString();

                if (things_id.equals(onlineThingsId)) {

                    Double onlineCount = Double.valueOf(Integer.valueOf(onlineMap.get("onlineCount").toString()));
                    Double dateCount = Double.valueOf(differentDays(startDate, endDate));

                    carOwnerMap.put("car_work_per", String.format("%.4f", onlineCount / dateCount));
                }
            });
        });

        List<Map<String, Object>> carRangMapList = new ArrayList<>();
        List<Map<String, Object>> rangAll = tSSsVehicleModelDao.getRangForCarOfCarWorkPer(params);
        rangAll.forEach(rangItem -> {
            carList.forEach(carItem -> {
                if (rangItem.get("car_id").equals(carItem.get("car_id"))) {
                    carItem.put("rang", rangItem.get("rang"));
                    carRangMapList.add(carItem);
                    return;
                }
            });
        });

        return carRangMapList;
    }

    @Override
    public PageInfo carOwnerEngineTotalHours(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);

        thinsList.forEach(item -> {
            String workHoursJson = toolCarDataMapper.getWorkHoursByDate(item.get("things_id").toString(), params.get("date").toString());
            item.put("workHoursJson", JSON.parseObject(workHoursJson));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public PageInfo carOwnerEngineTotalHoursOfDay(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);

        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            String workHoursJson = tSSsVehicleModelDao.getWorkHoursOfDay(params);

            //Feature.OrderedField 解决JSON.parseObject后排序变化
            item.put("workHoursJson", JSON.parseObject(workHoursJson, Feature.OrderedField));
            Object workHoursObject = JSON.parseObject(workHoursJson, Feature.OrderedField);
            Map<String, String> workHours = (Map<String, String>) workHoursObject;

            //查询天的总工时
            Double workHoursSum = 0.00;
            if (workHours != null) {
                for (String value : workHours.values()) {
                    workHoursSum = workHoursSum + Double.parseDouble(value);
                }
            }
            workHoursSum = Double.parseDouble(String.format("%.2f", workHoursSum));
            item.put("workHoursSum", String.valueOf(workHoursSum));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public PageInfo carOwnerEngineTotalHoursBetweenDay(Map<String, Object> params) {

        tSSsVehicleModelDao.group_concat_max_len();

        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        // 获取服务商下面的所有绑定设备的车辆，这里用户名
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThingsNew(params);

        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));

            // 获取每个车辆开机的天数
            String workDayCount = tSSsVehicleModelDao.getWorkDayCount(params);
            item.put("workDayCount",workDayCount);

            // 获取每个车辆的工时
            String workHoursJson = tSSsVehicleModelDao.getWorkHoursOfDay(params);

            //Feature.OrderedField 解决JSON.parseObject后排序变化
            item.put("workHoursJson", JSON.parseObject(workHoursJson, Feature.OrderedField));
            Object workHoursObject = JSON.parseObject(workHoursJson, Feature.OrderedField);
            Map<String, String> workHours = (Map<String, String>) workHoursObject;

            // 查询的每辆车的总工时，查出来的工时相加
            Double workHoursSum = 0.00;
            if (workHours != null) {
                for (String value : workHours.values()) {
                    workHoursSum = workHoursSum + Double.parseDouble(value);
                }
            }
            workHoursSum = Double.parseDouble(String.format("%.2f", workHoursSum));
            item.put("workHoursSum", String.valueOf(workHoursSum));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }


    @Override
    public List<Map<String, Object>> usernameList(Map<String, Object> params) {
//        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
//        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
//        PageHelper.startPage(currentPage, pageSize);
        // 获取服务商下面的所有绑定设备的车辆，这里用户名
        List<Map<String, Object>> selectUsernameList = tSSsVehicleModelDao.selectUsernameList(params);

        return selectUsernameList;
    }

    @Override
    public List<Map<String, Object>> bdCarList(Map<String, Object> params) {
//        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
//        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
//        PageHelper.startPage(currentPage, pageSize);
        // 获取服务商下面的所有绑定设备的车辆，这里用户名
        List<Map<String, Object>> selectUsernameList = tSSsVehicleModelDao.selectBdCarList(params);

        return selectUsernameList;
    }

    //
    @Override
    public List<Map<String, Object>> exportCarOwnerEngineTotalHoursOfDay(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineTotalHoursOfDay(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("workHoursJson") != null) {
                Map<String, Object> workHoursJson = (Map<String, Object>) map.get("workHoursJson");
                for (String str : workHoursJson.keySet()) {
                    value.put(str, workHoursJson.get(str) + "小时");
                }
            }
            if(map.get("workHoursSum") != null) {
                Double workHoursSum1 = Double.parseDouble(map.get("workHoursSum").toString());
                int day = (int) (workHoursSum1 / 24);
                int hour = (int) (workHoursSum1 % 24);
                int minutes = (int) (workHoursSum1 % 1 * 60);
                String workHoursSum1ToTime = day + "天" + hour + "小时" + minutes + "分钟"
                        + "\n"
                        + workHoursSum1 + "h";
                value.put("workHoursSum", workHoursSum1ToTime);
            }
            if(map.get("workHoursSum") != null) {
                Double workHoursSum = Double.parseDouble((String) map.get("workHoursSum"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                int days = 0;
                try {
                    days = 8 * (DateUtil.getDays(DateUtil.parseDate(sdf.format(sdf.parse(params.get("startDay").toString()))), DateUtil.parseDate(sdf.format(sdf.parse(params.get("endDay").toString())))) + 1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String availability = String.format("%.2f", workHoursSum / days * 100) + "%";
                value.put("availability", availability);
            }
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            dynamicColumBean.setFiledShowName(sdf.format(startTime));
            dynamicColumBean.setFiledCode(sdf.format(startTime));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            Calendar cc = Calendar.getInstance();
            cc.setTime(startTime);
            cc.add(cc.DATE, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanSum = new DynamicColumBean();
        dynamicColumBeanSum.setFiledShowName("工时合计");
        dynamicColumBeanSum.setFiledCode("workHoursSum");
        dynamicColumBeanSum.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanAvailability = new DynamicColumBean();
        dynamicColumBeanAvailability.setFiledShowName("利用率");
        dynamicColumBeanAvailability.setFiledCode("availability");
        dynamicColumBeanAvailability.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanSum);
        DynamicColumBeanList.add(dynamicColumBeanAvailability);
        return DynamicColumBeanList;
    }

    @Override
    public PageInfo carOwnerEngineTotalHoursOfWeek(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            String workHoursOfWeekJson = tSSsVehicleModelDao.getWorkHoursOfWeek(params);
            item.put("workHoursOfWeekJson", JSON.parseObject(workHoursOfWeekJson, Feature.OrderedField));
            Object workHoursOfWeekObject = JSON.parseObject(workHoursOfWeekJson, Feature.OrderedField);
            Map<String, String> workHours = (Map<String, String>) workHoursOfWeekObject;
            Double workHoursOfWeekSum = 0.00;
            if (workHours != null) {
                for (String value : workHours.values()) {
                    workHoursOfWeekSum = workHoursOfWeekSum + Double.parseDouble(value);
                }
            }
            workHoursOfWeekSum = Double.parseDouble(String.format("%.2f", workHoursOfWeekSum));
            item.put("workHoursWeekSum", String.valueOf(workHoursOfWeekSum));
        });


        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineTotalHoursOfWeek(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineTotalHoursOfWeek(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("workHoursOfWeekJson") != null) {
                Map<String, Object> workHoursOfWeekJson = (Map<String, Object>) map.get("workHoursOfWeekJson");
                for (String str : workHoursOfWeekJson.keySet()) {
                    value.put(str, workHoursOfWeekJson.get(str) + "小时");
                }
            }
            if(map.get("workHoursWeekSum") != null) {
                Double workHoursSum1 = Double.parseDouble(map.get("workHoursWeekSum").toString());
                int day = (int) (workHoursSum1 / 24);
                int hour = (int) (workHoursSum1 % 24);
                int minutes = (int) (workHoursSum1 % 1 * 60);
                String workHoursSum1ToTime = day + "天" + hour + "小时" + minutes + "分钟"
                        + "\n"
                        + workHoursSum1 + "h";
                value.put("workHoursWeekSum", workHoursSum1ToTime);
            }
            if(map.get("workHoursWeekSum") != null) {
                Double workHoursSum = Double.parseDouble((String) map.get("workHoursWeekSum"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                int hours = 0 ;
                try {
                    hours = 8 * (differentDays(sdf.parse(params.get("startDay").toString()), sdf.parse(params.get("endDay").toString())) + 1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String availability = String.format("%.2f", workHoursSum / hours * 100) + "%";
                value.put("availability", availability);
            }
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfWeekBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            Calendar cc = Calendar.getInstance();
            cc.setFirstDayOfWeek(Calendar.SUNDAY);
            cc.setMinimalDaysInFirstWeek(4);
            cc.setTime(startTime);
            dynamicColumBean.setFiledShowName(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.WEEK_OF_YEAR) >= 10 ? cc.get(Calendar.WEEK_OF_YEAR) : "0" + cc.get(Calendar.WEEK_OF_YEAR)));
            dynamicColumBean.setFiledCode(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.WEEK_OF_YEAR) >= 10 ? cc.get(Calendar.WEEK_OF_YEAR) : "0" + cc.get(Calendar.WEEK_OF_YEAR)));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            cc.add(cc.WEEK_OF_YEAR, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanSum = new DynamicColumBean();
        dynamicColumBeanSum.setFiledShowName("工时合计");
        dynamicColumBeanSum.setFiledCode("workHoursWeekSum");
        dynamicColumBeanSum.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanAvailability = new DynamicColumBean();
        dynamicColumBeanAvailability.setFiledShowName("利用率");
        dynamicColumBeanAvailability.setFiledCode("availability");
        dynamicColumBeanAvailability.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanSum);
        DynamicColumBeanList.add(dynamicColumBeanAvailability);
        return DynamicColumBeanList;
    }

    @Override
    public PageInfo carOwnerEngineTotalHoursOfMonth(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            String workHoursOfMonthJson = tSSsVehicleModelDao.getWorkHoursOfMonth(params);
            item.put("workHoursOfMonthJson", JSON.parseObject(workHoursOfMonthJson, Feature.OrderedField));
            Object workHoursOfMonthObject = JSON.parseObject(workHoursOfMonthJson, Feature.OrderedField);
            Map<String, String> workHours = (Map<String, String>) workHoursOfMonthObject;
            Double workHoursOfMonthSum = 0.00;
            if (workHours != null) {
                for (String value : workHours.values()) {
                    workHoursOfMonthSum = workHoursOfMonthSum + Double.parseDouble(value);
                }
            }
            workHoursOfMonthSum = Double.parseDouble(String.format("%.2f", workHoursOfMonthSum));
            item.put("workHoursMonthSum", String.valueOf(workHoursOfMonthSum));
        });


        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineTotalHoursOfMonth(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineTotalHoursOfMonth(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("workHoursOfMonthJson") != null) {
                Map<String, Object> workHoursOfMonthJson = (Map<String, Object>) map.get("workHoursOfMonthJson");
                for (String str : workHoursOfMonthJson.keySet()) {
                    value.put(str, workHoursOfMonthJson.get(str) + "小时");
                }
            }
            if(map.get("workHoursMonthSum") != null) {
                Double workHoursSum1 = Double.parseDouble(map.get("workHoursMonthSum").toString());
                int day = (int) (workHoursSum1 / 24);
                int hour = (int) (workHoursSum1 % 24);
                int minutes = (int) (workHoursSum1 % 1 * 60);
                String workHoursSum1ToTime = day + "天" + hour + "小时" + minutes + "分钟"
                        + "\n"
                        + workHoursSum1 + "h";
                value.put("workHoursMonthSum", workHoursSum1ToTime);
            }
            if(map.get("workHoursMonthSum") != null) {
                Double workHoursSum = Double.parseDouble((String) map.get("workHoursMonthSum"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                int hours = 0 ;
                try {
                    hours = 8 * (differentDays(sdf.parse(params.get("startDay").toString()), sdf.parse(params.get("endDay").toString())) + 1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String availability = String.format("%.2f", workHoursSum / hours * 100) + "%";
                value.put("availability", availability);
            }
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfMonthBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            Calendar cc = Calendar.getInstance();
            cc.setFirstDayOfWeek(Calendar.SUNDAY);
            cc.setTime(startTime);
            dynamicColumBean.setFiledShowName(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.MONTH) + 1 >= 10 ? cc.get(Calendar.MONTH) + 1 : "0" + (cc.get(Calendar.MONTH) + 1)));
            dynamicColumBean.setFiledCode(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.MONTH) + 1 >= 10 ? cc.get(Calendar.MONTH) + 1 : "0" + (cc.get(Calendar.MONTH) + 1)));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            cc.add(cc.MONTH, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanSum = new DynamicColumBean();
        dynamicColumBeanSum.setFiledShowName("工时合计");
        dynamicColumBeanSum.setFiledCode("workHoursMonthSum");
        dynamicColumBeanSum.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanAvailability = new DynamicColumBean();
        dynamicColumBeanAvailability.setFiledShowName("利用率");
        dynamicColumBeanAvailability.setFiledCode("availability");
        dynamicColumBeanAvailability.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanSum);
        DynamicColumBeanList.add(dynamicColumBeanAvailability);
        return DynamicColumBeanList;
    }

    //按日、周、月查询时间段内所有车辆的总工时
    @Override
    public String carOwnerEngineGetTotalHours(Map<String, Object> params) {
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        Double totalHours = 0.00;
        for (Map<String, Object> item : thinsList) {
            params.put("things_id", item.get("things_id"));
            String totalWorkHours = tSSsVehicleModelDao.getTotalHours(params);
            totalHours = totalHours + Double.valueOf(totalWorkHours);
        }
        String totalWorkHours = String.valueOf(totalHours);
        return totalWorkHours;
    }

    //按日、周、月查询时间段内所有车辆的总工时,拆分车主和设备名称的搜索条件
    @Override
    public String carOwnerEngineGetTotalHoursNew(Map<String, Object> params) {
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThingsNew(params);
        Double totalHours = 0.00;
        for (Map<String, Object> item : thinsList) {
            params.put("things_id", item.get("things_id"));
            String totalWorkHours = tSSsVehicleModelDao.getTotalHours(params);
            totalHours = totalHours + Double.valueOf(totalWorkHours);
        }
        String totalWorkHours = String.valueOf(totalHours);
        return totalWorkHours;
    }

    // 按日、周、月查询时间段内所有车辆的总开机天数,拆分车主和设备名称的搜索条件
    @Override
    public String carOwnerEngineGetTotalDays(Map<String, Object> params) {

        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThingsNew(params);
        Double totalDays = 0.00;
        for (Map<String, Object> item : thinsList) {
            params.put("things_id", item.get("things_id"));
            String workDayCount = tSSsVehicleModelDao.getWorkDayCount(params);
            if(workDayCount != null ){
                totalDays = totalDays + Double.valueOf(workDayCount);
            }
        }

        String totalWorkDays = String.valueOf(totalDays);
        return totalWorkDays;
    }

    //按24H查询某一天所有车辆的总工时
    @Override
    public String carOwnerEngineGetTotalHoursOf24H(Map<String, Object> params) {
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        Double totalHours = 0.00;
        for (Map<String, Object> item : thinsList) {
            params.put("things_id", item.get("things_id"));
//            String totalWorkHours = tSSsVehicleModelDao.getTotalHoursOf24H(params);
//            totalHours = totalHours + Double.valueOf(totalWorkHours);
            String workHoursJson = toolCarDataMapper.getWorkHoursByDate(item.get("things_id").toString(), params.get("date").toString());
            Object workHoursObject = JSON.parseObject(workHoursJson, Feature.OrderedField);
            Map<String, Object> workHours = (Map<String, Object>) workHoursObject;
            if (workHours != null) {
                totalHours = totalHours + Double.parseDouble(workHours.get("workHours").toString());
            }
        }
        String totalWorkHours = String.valueOf(totalHours);
        return totalWorkHours;
    }

    @Override
    public PageInfo carOwnerEngineTotalFuelConsumptionOfDay(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            String fuelConsumptionOfDayJson = tSSsVehicleModelDao.getFuelConsumptionOfDay(params);
            item.put("fuelConsumptionOfDayJson", JSON.parseObject(fuelConsumptionOfDayJson, Feature.OrderedField));
            Object fuelConsumptionOfDayObject = JSON.parseObject(fuelConsumptionOfDayJson, Feature.OrderedField);
            Map<String, String> fuelConsumption = (Map<String, String>) fuelConsumptionOfDayObject;
            Double fuelConsumptionOfDaySum = 0.00;
            Double fuelConsumptionOfDayAverage = 0.00;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            if (fuelConsumption != null) {
                for (String value : fuelConsumption.values()) {
                    fuelConsumptionOfDaySum = fuelConsumptionOfDaySum + Double.parseDouble(value);
                }
            }

            //计算相差天数算出时间段内：加油量/天(平均加油量)
            try {
                Date startDay = formatter.parse((String) params.get("startDay"));
                Date endDay = formatter.parse((String) params.get("endDay"));
                double diffDay = (endDay.getTime() - startDay.getTime()) / (1000 * 60 * 60 * 24) + 1;
                fuelConsumptionOfDayAverage = fuelConsumptionOfDaySum / diffDay;
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //保留两位小数
            fuelConsumptionOfDaySum = Double.parseDouble(String.format("%.2f", fuelConsumptionOfDaySum));
            fuelConsumptionOfDayAverage = Double.parseDouble(String.format("%.2f", fuelConsumptionOfDayAverage));
            item.put("fuelConsumptionOfDaySum", String.valueOf(fuelConsumptionOfDaySum));
            item.put("fuelConsumptionOfDayAverage", String.valueOf(fuelConsumptionOfDayAverage));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineTotalFuelConsumptionOfDay(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineTotalFuelConsumptionOfDay(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("fuelConsumptionOfDayJson") != null) {
                Map<String, Object> fuelConsumptionOfDayJson = (Map<String, Object>) map.get("fuelConsumptionOfDayJson");
                for (String str : fuelConsumptionOfDayJson.keySet()) {
                    value.put(str, fuelConsumptionOfDayJson.get(str) + "升");
                }
            }
            value.put("fuelConsumptionOfDaySum", map.get("fuelConsumptionOfDaySum") + "升");
            value.put("fuelConsumptionOfDayAverage", map.get("fuelConsumptionOfDayAverage") + "升");
            value.put("region_name", map.get("region_name"));
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfFuelDayBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            dynamicColumBean.setFiledShowName(sdf.format(startTime));
            dynamicColumBean.setFiledCode(sdf.format(startTime));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            Calendar cc = Calendar.getInstance();
            cc.setTime(startTime);
            cc.add(cc.DATE, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanSum = new DynamicColumBean();
        dynamicColumBeanSum.setFiledShowName("合计");
        dynamicColumBeanSum.setFiledCode("fuelConsumptionOfDaySum");
        dynamicColumBeanSum.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanFCODA = new DynamicColumBean();
        dynamicColumBeanFCODA.setFiledShowName("平均值");
        dynamicColumBeanFCODA.setFiledCode("fuelConsumptionOfDayAverage");
        dynamicColumBeanFCODA.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanRegion = new DynamicColumBean();
        dynamicColumBeanRegion.setFiledShowName("地区");
        dynamicColumBeanRegion.setFiledCode("region_name");
        dynamicColumBeanRegion.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanSum);
        DynamicColumBeanList.add(dynamicColumBeanFCODA);
        DynamicColumBeanList.add(dynamicColumBeanRegion);
        return DynamicColumBeanList;
    }

    @Override
    public PageInfo carOwnerEngineTotalFuelConsumptionOfWeek(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            String fuelConsumptionOfWeekJson = tSSsVehicleModelDao.getFuelConsumptionOfWeek(params);
            item.put("fuelConsumptionOfWeekJson", JSON.parseObject(fuelConsumptionOfWeekJson, Feature.OrderedField));
            Object fuelConsumptionOfWeekObject = JSON.parseObject(fuelConsumptionOfWeekJson, Feature.OrderedField);
            Map<String, String> fuelConsumption = (Map<String, String>) fuelConsumptionOfWeekObject;
            Double fuelConsumptionOfWeekSum = 0.00;
            Double fuelConsumptionOfWeekAverage = 0.00;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            if (fuelConsumption != null) {
                for (String value : fuelConsumption.values()) {
                    fuelConsumptionOfWeekSum = fuelConsumptionOfWeekSum + Double.parseDouble(value);
                }
            }

            //计算相差天数算出时间段内：加油量/天(平均加油量)
            try {
                Date startDay = formatter.parse((String) params.get("startDay"));
                Date endDay = formatter.parse((String) params.get("endDay"));
                double diffWeek = ((endDay.getTime() - startDay.getTime()) / (1000 * 60 * 60 * 24) + 1) / 7 + 1;
                fuelConsumptionOfWeekAverage = fuelConsumptionOfWeekSum / diffWeek;
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //保留两位小数
            fuelConsumptionOfWeekSum = Double.parseDouble(String.format("%.2f", fuelConsumptionOfWeekSum));
            fuelConsumptionOfWeekAverage = Double.parseDouble(String.format("%.2f", fuelConsumptionOfWeekAverage));
            item.put("fuelConsumptionOfWeekSum", String.valueOf(fuelConsumptionOfWeekSum));
            item.put("fuelConsumptionOfWeekAverage", String.valueOf(fuelConsumptionOfWeekAverage));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineTotalFuelConsumptionOfWeek(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineTotalFuelConsumptionOfWeek(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("fuelConsumptionOfWeekJson") != null) {
                Map<String, Object> fuelConsumptionOfWeekJson = (Map<String, Object>) map.get("fuelConsumptionOfWeekJson");
                for (String str : fuelConsumptionOfWeekJson.keySet()) {
                    value.put(str, fuelConsumptionOfWeekJson.get(str) + "升");
                }
            }
            value.put("fuelConsumptionOfWeekSum", map.get("fuelConsumptionOfWeekSum") + "升");
            value.put("fuelConsumptionOfWeekAverage", map.get("fuelConsumptionOfWeekAverage") + "升");
            value.put("region_name", map.get("region_name"));
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfFuelWeekBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            Calendar cc = Calendar.getInstance();
            cc.setFirstDayOfWeek(Calendar.SUNDAY);
            cc.setMinimalDaysInFirstWeek(4);
            cc.setTime(startTime);
            dynamicColumBean.setFiledShowName(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.WEEK_OF_YEAR) >= 10 ? cc.get(Calendar.WEEK_OF_YEAR) : "0" + cc.get(Calendar.WEEK_OF_YEAR)));
            dynamicColumBean.setFiledCode(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.WEEK_OF_YEAR) >= 10 ? cc.get(Calendar.WEEK_OF_YEAR) : "0" + cc.get(Calendar.WEEK_OF_YEAR)));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            cc.add(cc.WEEK_OF_YEAR, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanSum = new DynamicColumBean();
        dynamicColumBeanSum.setFiledShowName("合计");
        dynamicColumBeanSum.setFiledCode("fuelConsumptionOfWeekSum");
        dynamicColumBeanSum.setOrderNum(i);

        i = i++;
        //名字太长缩写
        DynamicColumBean dynamicColumBeanFCOWA = new DynamicColumBean();
        dynamicColumBeanFCOWA.setFiledShowName("平均值");
        dynamicColumBeanFCOWA.setFiledCode("fuelConsumptionOfWeekAverage");
        dynamicColumBeanFCOWA.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanRegion = new DynamicColumBean();
        dynamicColumBeanRegion.setFiledShowName("地区");
        dynamicColumBeanRegion.setFiledCode("region_name");
        dynamicColumBeanRegion.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanSum);
        DynamicColumBeanList.add(dynamicColumBeanFCOWA);
        DynamicColumBeanList.add(dynamicColumBeanRegion);
        return DynamicColumBeanList;
    }

    @Override
    public PageInfo carOwnerEngineTotalFuelConsumptionOfMonth(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            String fuelConsumptionOfMonthJson = tSSsVehicleModelDao.getFuelConsumptionOfMonth(params);
            item.put("fuelConsumptionOfMonthJson", JSON.parseObject(fuelConsumptionOfMonthJson, Feature.OrderedField));
            Object fuelConsumptionOfMonthObject = JSON.parseObject(fuelConsumptionOfMonthJson, Feature.OrderedField);
            Map<String, String> fuelConsumption = (Map<String, String>) fuelConsumptionOfMonthObject;
            Double fuelConsumptionOfMonthSum = 0.00;
            Double fuelConsumptionOfMonthAverage = 0.00;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            if (fuelConsumption != null) {
                for (String value : fuelConsumption.values()) {
                    fuelConsumptionOfMonthSum = fuelConsumptionOfMonthSum + Double.parseDouble(value);
                }
            }

            //计算相差天数算出时间段内：加油量/天(平均加油量)
            try {
                Date startDay = formatter.parse((String) params.get("startDay"));
                Date endDay = formatter.parse((String) params.get("endDay"));
                double diffMonth = ((endDay.getTime() - startDay.getTime()) / (1000 * 60 * 60 * 24) + 1) / 30 + 1;
                fuelConsumptionOfMonthAverage = fuelConsumptionOfMonthSum / diffMonth;
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //保留两位小数
            fuelConsumptionOfMonthSum = Double.parseDouble(String.format("%.2f", fuelConsumptionOfMonthSum));
            fuelConsumptionOfMonthAverage = Double.parseDouble(String.format("%.2f", fuelConsumptionOfMonthAverage));
            item.put("fuelConsumptionOfMonthSum", String.valueOf(fuelConsumptionOfMonthSum));
            item.put("fuelConsumptionOfMonthAverage", String.valueOf(fuelConsumptionOfMonthAverage));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineTotalFuelConsumptionOfMonth(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineTotalFuelConsumptionOfMonth(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("fuelConsumptionOfMonthJson") != null) {
                Map<String, Object> fuelConsumptionOfMonthJson = (Map<String, Object>) map.get("fuelConsumptionOfMonthJson");
                for (String str : fuelConsumptionOfMonthJson.keySet()) {
                    value.put(str, fuelConsumptionOfMonthJson.get(str) + "升");
                }
            }
            value.put("fuelConsumptionOfMonthSum", map.get("fuelConsumptionOfMonthSum") + "升");
            value.put("fuelConsumptionOfMonthAverage", map.get("fuelConsumptionOfMonthAverage") + "升");
            value.put("region_name", map.get("region_name"));
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfFuelMonthBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            Calendar cc = Calendar.getInstance();
            cc.setFirstDayOfWeek(Calendar.SUNDAY);
            cc.setTime(startTime);
            dynamicColumBean.setFiledShowName(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.MONTH) + 1 >= 10 ? cc.get(Calendar.MONTH) + 1 : "0" + (cc.get(Calendar.MONTH) + 1)));
            dynamicColumBean.setFiledCode(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.MONTH) + 1 >= 10 ? cc.get(Calendar.MONTH) + 1 : "0" + (cc.get(Calendar.MONTH) + 1)));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            cc.add(cc.MONTH, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanSum = new DynamicColumBean();
        dynamicColumBeanSum.setFiledShowName("合计");
        dynamicColumBeanSum.setFiledCode("fuelConsumptionOfMonthSum");
        dynamicColumBeanSum.setOrderNum(i);

        i = i++;
        //名字太长缩写
        DynamicColumBean dynamicColumBeanAverage = new DynamicColumBean();
        dynamicColumBeanAverage.setFiledShowName("平均值");
        dynamicColumBeanAverage.setFiledCode("fuelConsumptionOfMonthAverage");
        dynamicColumBeanAverage.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanRegion = new DynamicColumBean();
        dynamicColumBeanRegion.setFiledShowName("地区");
        dynamicColumBeanRegion.setFiledCode("region_name");
        dynamicColumBeanRegion.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanSum);
        DynamicColumBeanList.add(dynamicColumBeanAverage);
        DynamicColumBeanList.add(dynamicColumBeanRegion);
        return DynamicColumBeanList;
    }

    @Override
    public String carOwnerEngineGetTotalFuelConsumption(Map<String, Object> params) {
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        Double totalFuelConsumption = 0.00;
        for (Map<String, Object> item : thinsList) {
            params.put("things_id", item.get("things_id"));
            String fuelConsumption = tSSsVehicleModelDao.getTotalFuelConsumption(params);
            totalFuelConsumption = totalFuelConsumption + Double.valueOf(fuelConsumption);
        }
        String totalFuelConsumptions = String.valueOf(totalFuelConsumption);
        return totalFuelConsumptions;
    }

    @Override
    public String carOwnerEngineGetTotalFuelConsumptionNew(Map<String, Object> params) {
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThingsNew(params);
        Double totalFuelConsumption = 0.00;
        for (Map<String, Object> item : thinsList) {
            params.put("things_id", item.get("things_id"));
            String fuelConsumption = tSSsVehicleModelDao.getTotalFuelConsumption(params);
            totalFuelConsumption = totalFuelConsumption + Double.valueOf(fuelConsumption);
        }
        String totalFuelConsumptions = String.valueOf(totalFuelConsumption);
        return totalFuelConsumptions;
    }

    @Override
    public PageInfo carOwnerEngineFuelConsumptionAnalysisOfDay(Map<String, Object> params) {
        tSSsVehicleModelDao.group_concat_max_len();
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            params.put("car_model_id", item.get("car_model_id"));
            String fuelConsumptionAnalysisOfDayJson = tSSsVehicleModelDao.getFuelConsumptionAnalysisOfDay(params);
            item.put("fuelConsumptionAnalysisOfDayJson", JSON.parseObject(fuelConsumptionAnalysisOfDayJson, Feature.OrderedField));
            String fuelConsumptionOfDayAvg = tSSsVehicleModelDao.getFuelConsumptionAvg(params);
            item.put("fuelConsumptionOfDayAvg", JSON.parseObject(fuelConsumptionOfDayAvg));
            String fuelConsumptionOfDaySimilarAvg = tSSsVehicleModelDao.getFuelConsumptionSimilarAvg(params);
            item.put("fuelConsumptionOfDaySimilarAvg", JSON.parseObject(fuelConsumptionOfDaySimilarAvg));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }



    @Override
    public Double carOwnerEngineFuelConsumptionAnalysisBetweenDaysum(Map<String, Object> params) {
        tSSsVehicleModelDao.group_concat_max_len();
        Integer pageSize =99999;
        Integer currentPage = 1;
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThingsNew(params);
        final double[] totalAverageFuelConsumptionSum = {0.0};  // 使用数组包装以满足final要求
        AtomicInteger totalDeviceCount = new AtomicInteger(0);  // 使用 AtomicInteger
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            params.put("car_model_id", item.get("car_model_id"));
            String fuelConsumptionAnalysisOfDayJson = tSSsVehicleModelDao.getFuelConsumptionAnalysisOfDay(params);
            item.put("fuelConsumptionAnalysisOfDayJson", JSON.parseObject(fuelConsumptionAnalysisOfDayJson, Feature.OrderedField));
            String fuelConsumptionOfDayAvg = tSSsVehicleModelDao.getFuelConsumptionAvg(params);
            item.put("fuelConsumptionOfDayAvg", JSON.parseObject(fuelConsumptionOfDayAvg));
            //
            String fuelConsumptionOfDaySimilarAvg = tSSsVehicleModelDao.getFuelConsumptionSimilarAvg(params);
            item.put("fuelConsumptionOfDaySimilarAvg", JSON.parseObject(fuelConsumptionOfDaySimilarAvg));

            // 单个车单位时间的油耗
//            String fuelConsumptionOfDaySimilarAvg = tSSsVehicleModelDao.getFuelConsumptionSimilarAvg(params);
            String fuelConsumptionSingle = tSSsVehicleModelDao.getTotalFuelConsumption(params);
            item.put("fuel_consumption_single", fuelConsumptionSingle);

            // 获取每个车辆工作的天数
            String workDayCount = tSSsVehicleModelDao.getWorkDayCount(params);
            item.put("workDayCount",workDayCount);

            // 平均油耗 保留两位小数
            String fuel_consumption_avg_single = "0.00";
            if(workDayCount != null && fuelConsumptionSingle!=null){
                Double fuel_consumption_avg_single_d = Double.parseDouble(fuelConsumptionSingle)/Double.parseDouble(workDayCount);
                fuel_consumption_avg_single =   String.format("%.2f", fuel_consumption_avg_single_d);
            }
            item.put("fuel_consumption_avg_single",fuel_consumption_avg_single);

            // 把之前的json数据转成map，直接返回,方便前端获取
            // 平均油耗
            String fuel_consumption_avg = "";
            // 总油耗
            String fuel_consumption_total = "";
            if(fuelConsumptionOfDaySimilarAvg !=null && !fuelConsumptionOfDaySimilarAvg.equals("")){
                Map<String, Object> fuelConsumption = (Map<String, Object>) JSON.parseObject(fuelConsumptionOfDaySimilarAvg);
                fuel_consumption_total = fuelConsumption.get("fuel_consumption_total").toString();
                fuel_consumption_avg = fuelConsumption.get("fuel_consumption_avg").toString();
            }

            item.put("fuel_consumption_total",fuel_consumption_total);
            item.put("fuel_consumption_avg",fuel_consumption_avg);

            // 单个车辆油耗
            // 单车平均油耗
//            String fuel_consumption_avg_single = "";
            // 总油耗
//            String fuel_consumption_single = "";
            String fuelConsumptionSingleCar = tSSsVehicleModelDao.getFuelConsumptionSingleCar(params);

            item.put("fuelConsumptionSingleCar", JSON.parseObject(fuelConsumptionSingleCar));
            if(fuelConsumptionSingleCar !=null && !fuelConsumptionSingleCar.equals("")){
                Map<String, Object> fuelConsumption = (Map<String, Object>) JSON.parseObject(fuelConsumptionOfDaySimilarAvg);
//                if(fuelConsumption.get("fuel_consumption_single") != null){
//                    fuel_consumption_single = fuelConsumption.get("fuel_consumption_single").toString();
//                }
                if(fuelConsumption.get("fuel_consumption_avg_single") != null){
                    fuel_consumption_avg_single = fuelConsumption.get("fuel_consumption_avg_single").toString();
                }
            }

//            item.put("fuel_consumption_single_old",fuel_consumption_single);
//            item.put("fuel_consumption_avg_single",fuel_consumption_avg_single);

            // 时间内的加油量(加油量压根没有，只有油耗量)
            String fuelConsumptionOfDayJson = tSSsVehicleModelDao.getFuelConsumptionOfDay(params);
            item.put("fuelConsumptionOfDayJson", JSON.parseObject(fuelConsumptionOfDayJson, Feature.OrderedField));
            Object fuelConsumptionOfDayObject = JSON.parseObject(fuelConsumptionOfDayJson, Feature.OrderedField);
            Map<String, String> fuelConsumption = (Map<String, String>) fuelConsumptionOfDayObject;
            Double fuelConsumptionOfDaySum = 0.00;
            Double fuelConsumptionOfDayAverage = 0.00;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            if (fuelConsumption != null) {
                for (String value : fuelConsumption.values()) {
                    fuelConsumptionOfDaySum = fuelConsumptionOfDaySum + Double.parseDouble(value);
                }
            }

            //计算相差天数算出时间段内：加油量/天(平均加油量)
            try {
                Date startDay = formatter.parse((String) params.get("startDay"));
                Date endDay = formatter.parse((String) params.get("endDay"));
                double diffDay = (endDay.getTime() - startDay.getTime()) / (1000 * 60 * 60 * 24) + 1;
                fuelConsumptionOfDayAverage = fuelConsumptionOfDaySum / diffDay;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // 累加到总和
            totalAverageFuelConsumptionSum[0] += Double.parseDouble(fuel_consumption_avg_single);
            if ( Double.parseDouble(fuel_consumption_avg_single)>0){
                // 增加设备数量
                totalDeviceCount.incrementAndGet();
            }


            //保留两位小数
            fuelConsumptionOfDaySum = Double.parseDouble(String.format("%.2f", fuelConsumptionOfDaySum));
            fuelConsumptionOfDayAverage = Double.parseDouble(String.format("%.2f", fuelConsumptionOfDayAverage));
            item.put("fuelConsumptionOfDaySum", String.valueOf(fuelConsumptionOfDaySum));
            item.put("fuelConsumptionOfDayAverage", String.valueOf(fuelConsumptionOfDayAverage));

        });
        // 计算总平均油耗量
        double totalAverageFuelConsumption = totalAverageFuelConsumptionSum[0] / totalDeviceCount.get();
        System.out.println(totalAverageFuelConsumption);
        Map<String,Object> sum=new HashMap<>();
        sum.put("totalAverageFuelConsumption",totalAverageFuelConsumption);
        thinsList.add(sum);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return totalAverageFuelConsumption;
    }


    @Override
    public PageInfo carOwnerEngineFuelConsumptionAnalysisBetweenDay(Map<String, Object> params) {
        tSSsVehicleModelDao.group_concat_max_len();
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThingsNew(params);
        final double[] totalAverageFuelConsumptionSum = {0.0};  // 使用数组包装以满足final要求
        AtomicInteger totalDeviceCount = new AtomicInteger(0);  // 使用 AtomicInteger
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            params.put("car_model_id", item.get("car_model_id"));
            String fuelConsumptionAnalysisOfDayJson = tSSsVehicleModelDao.getFuelConsumptionAnalysisOfDay(params);
            item.put("fuelConsumptionAnalysisOfDayJson", JSON.parseObject(fuelConsumptionAnalysisOfDayJson, Feature.OrderedField));
            String fuelConsumptionOfDayAvg = tSSsVehicleModelDao.getFuelConsumptionAvg(params);
            item.put("fuelConsumptionOfDayAvg", JSON.parseObject(fuelConsumptionOfDayAvg));
            //
            String fuelConsumptionOfDaySimilarAvg = tSSsVehicleModelDao.getFuelConsumptionSimilarAvg(params);
            item.put("fuelConsumptionOfDaySimilarAvg", JSON.parseObject(fuelConsumptionOfDaySimilarAvg));

            // 单个车单位时间的油耗
//            String fuelConsumptionOfDaySimilarAvg = tSSsVehicleModelDao.getFuelConsumptionSimilarAvg(params);
            String fuelConsumptionSingle = tSSsVehicleModelDao.getTotalFuelConsumption(params);
            item.put("fuel_consumption_single", fuelConsumptionSingle);

            // 获取每个车辆工作的天数
            String workDayCount = tSSsVehicleModelDao.getWorkDayCount(params);
            item.put("workDayCount",workDayCount);

            // 平均油耗 保留两位小数
            String fuel_consumption_avg_single = "0.00";
            if(workDayCount != null && fuelConsumptionSingle!=null){
                Double fuel_consumption_avg_single_d = Double.parseDouble(fuelConsumptionSingle)/Double.parseDouble(workDayCount);
                fuel_consumption_avg_single =   String.format("%.2f", fuel_consumption_avg_single_d);
            }
            item.put("fuel_consumption_avg_single",fuel_consumption_avg_single);

            // 把之前的json数据转成map，直接返回,方便前端获取
            // 平均油耗
            String fuel_consumption_avg = "";
            // 总油耗
            String fuel_consumption_total = "";
            if(fuelConsumptionOfDaySimilarAvg !=null && !fuelConsumptionOfDaySimilarAvg.equals("")){
                Map<String, Object> fuelConsumption = (Map<String, Object>) JSON.parseObject(fuelConsumptionOfDaySimilarAvg);
                fuel_consumption_total = fuelConsumption.get("fuel_consumption_total").toString();
                fuel_consumption_avg = fuelConsumption.get("fuel_consumption_avg").toString();
            }

            item.put("fuel_consumption_total",fuel_consumption_total);
            item.put("fuel_consumption_avg",fuel_consumption_avg);

            // 单个车辆油耗
            // 单车平均油耗
//            String fuel_consumption_avg_single = "";
            // 总油耗
//            String fuel_consumption_single = "";
            String fuelConsumptionSingleCar = tSSsVehicleModelDao.getFuelConsumptionSingleCar(params);

            item.put("fuelConsumptionSingleCar", JSON.parseObject(fuelConsumptionSingleCar));
            if(fuelConsumptionSingleCar !=null && !fuelConsumptionSingleCar.equals("")){
                Map<String, Object> fuelConsumption = (Map<String, Object>) JSON.parseObject(fuelConsumptionOfDaySimilarAvg);
//                if(fuelConsumption.get("fuel_consumption_single") != null){
//                    fuel_consumption_single = fuelConsumption.get("fuel_consumption_single").toString();
//                }
                if(fuelConsumption.get("fuel_consumption_avg_single") != null){
                    fuel_consumption_avg_single = fuelConsumption.get("fuel_consumption_avg_single").toString();
                }
            }

//            item.put("fuel_consumption_single_old",fuel_consumption_single);
//            item.put("fuel_consumption_avg_single",fuel_consumption_avg_single);

            // 时间内的加油量(加油量压根没有，只有油耗量)
            String fuelConsumptionOfDayJson = tSSsVehicleModelDao.getFuelConsumptionOfDay(params);
            item.put("fuelConsumptionOfDayJson", JSON.parseObject(fuelConsumptionOfDayJson, Feature.OrderedField));
            Object fuelConsumptionOfDayObject = JSON.parseObject(fuelConsumptionOfDayJson, Feature.OrderedField);
            Map<String, String> fuelConsumption = (Map<String, String>) fuelConsumptionOfDayObject;
            Double fuelConsumptionOfDaySum = 0.00;
            Double fuelConsumptionOfDayAverage = 0.00;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            if (fuelConsumption != null) {
                for (String value : fuelConsumption.values()) {
                    fuelConsumptionOfDaySum = fuelConsumptionOfDaySum + Double.parseDouble(value);
                }
            }

            //计算相差天数算出时间段内：加油量/天(平均加油量)
            try {
                Date startDay = formatter.parse((String) params.get("startDay"));
                Date endDay = formatter.parse((String) params.get("endDay"));
                double diffDay = (endDay.getTime() - startDay.getTime()) / (1000 * 60 * 60 * 24) + 1;
                fuelConsumptionOfDayAverage = fuelConsumptionOfDaySum / diffDay;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // 累加到总和
            totalAverageFuelConsumptionSum[0] += Double.parseDouble(fuel_consumption_avg_single);
            if ( Double.parseDouble(fuel_consumption_avg_single)>0){
                // 增加设备数量
                totalDeviceCount.incrementAndGet();
            }


            //保留两位小数
            fuelConsumptionOfDaySum = Double.parseDouble(String.format("%.2f", fuelConsumptionOfDaySum));
            fuelConsumptionOfDayAverage = Double.parseDouble(String.format("%.2f", fuelConsumptionOfDayAverage));
            item.put("fuelConsumptionOfDaySum", String.valueOf(fuelConsumptionOfDaySum));
            item.put("fuelConsumptionOfDayAverage", String.valueOf(fuelConsumptionOfDayAverage));

        });
        // 计算总平均油耗量
//        double totalAverageFuelConsumption1 = this.carOwnerEngineFuelConsumptionAnalysisBetweenDaysum(params);
//        String formattedValue = String.format("%.2f",totalAverageFuelConsumption1);
//        double totalAverageFuelConsumption = Double.parseDouble(formattedValue);
//        Map<String,Object> sum=new HashMap<>();
//        sum.put("totalAverageFuelConsumption",totalAverageFuelConsumption);
//        thinsList.add(sum);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineFuelConsumptionAnalysisOfDay(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineFuelConsumptionAnalysisOfDay(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("fuelConsumptionAnalysisOfDayJson") != null) {
                Map<String, Object> fuelConsumptionAnalysisOfDayJson = (Map<String, Object>) map.get("fuelConsumptionAnalysisOfDayJson");
                for (String str : fuelConsumptionAnalysisOfDayJson.keySet()) {
                    if (fuelConsumptionAnalysisOfDayJson.get(str) != null) {
                        Map<String, Object> detailObject = (Map<String, Object>) fuelConsumptionAnalysisOfDayJson.get(str);
                        String dayDetail = "平均油耗：" + detailObject.get("fuelConsumption")
                                + "升/时" + "\n"
                                + "工时：" + detailObject.get("fuelConsumptionAvg")
                                + "小时" + "\n"
                                + "耗油量：" + detailObject.get("workHours")
                                + "升";
                        value.put(str, dayDetail);
                    }
                }
            }
            String avgDetailAvg = null;
            if (map.get("fuelConsumptionOfDayAvg") != null) {
                Map<String, Object> avgDetailObject = (Map<String, Object>) map.get("fuelConsumptionOfDayAvg");
                String avgDetail = "油耗：" + avgDetailObject.get("fuel_consumption_avg")
                        + "升/时" + "\n"
                        + "总工时：" + avgDetailObject.get("work_hours_total")
                        + "小时" + "\n"
                        + "总耗油量：" + avgDetailObject.get("fuel_consumption_total")
                        + "升";
                value.put("fuelConsumptionOfDayAvg", avgDetail);
                avgDetailAvg =  avgDetailObject.get("fuel_consumption_avg").toString();
            }

            if (map.get("fuelConsumptionOfDaySimilarAvg") != null) {
                Map<String, Object> similarAvgDetailObject = (Map<String, Object>) map.get("fuelConsumptionOfDaySimilarAvg");
                String similarAvgDetail = "油耗：" + similarAvgDetailObject.get("fuel_consumption_avg")
                        + "升/时" + "\n"
                        + "差额：" + String.format("%.2f",(Double.parseDouble(avgDetailAvg != null ? avgDetailAvg : "0") - Double.parseDouble(similarAvgDetailObject.get("fuel_consumption_avg").toString() != null ? similarAvgDetailObject.get("fuel_consumption_avg").toString() : "0")))
                        + "升/时";
                value.put("fuelConsumptionOfDaySimilarAvg", similarAvgDetail);
            }

            value.put("region_name", map.get("region_name"));
            list.add(value);
        });
        return list;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineFuelConsumptionAnalysisBetweenDay(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineFuelConsumptionAnalysisBetweenDay(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("user_name", map.get("user_name"));
            value.put("mobile_phone", map.get("mobile_phone"));
            value.put("fuel_consumption_single", map.get("fuel_consumption_single"));
            value.put("fuel_consumption_avg_single", map.get("fuel_consumption_avg_single"));
            value.put("region_name", map.get("region_name"));
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfFuelAnalysisDayBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            dynamicColumBean.setFiledShowName(sdf.format(startTime));
            dynamicColumBean.setFiledCode(sdf.format(startTime));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            Calendar cc = Calendar.getInstance();
            cc.setTime(startTime);
            cc.add(cc.DATE, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanAvg = new DynamicColumBean();
        dynamicColumBeanAvg.setFiledShowName("平均值");
        dynamicColumBeanAvg.setFiledCode("fuelConsumptionOfDayAvg");
        dynamicColumBeanAvg.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanSimilarAvg = new DynamicColumBean();
        dynamicColumBeanSimilarAvg.setFiledShowName("同类平均值");
        dynamicColumBeanSimilarAvg.setFiledCode("fuelConsumptionOfDaySimilarAvg");
        dynamicColumBeanSimilarAvg.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanRegion = new DynamicColumBean();
        dynamicColumBeanRegion.setFiledShowName("地区");
        dynamicColumBeanRegion.setFiledCode("region_name");
        dynamicColumBeanRegion.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanAvg);
        DynamicColumBeanList.add(dynamicColumBeanSimilarAvg);
        DynamicColumBeanList.add(dynamicColumBeanRegion);
        return DynamicColumBeanList;
    }

    @Override
    public List<DynamicColumBean> getColumOfFuelAnalysisDayBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();

        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("机型");
        dynamicColumBean1.setFiledCode("model");
        dynamicColumBean1.setOrderNum(1);

        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("设备名称");
        dynamicColumBean2.setFiledCode("advice_name");
        dynamicColumBean2.setOrderNum(2);

        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("车主姓名");
        dynamicColumBean3.setFiledCode("user_name");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBean dynamicColumBean4 = new DynamicColumBean();
        dynamicColumBean4.setFiledShowName("车主电话");
        dynamicColumBean4.setFiledCode("mobile_phone");
        dynamicColumBean4.setOrderNum(4);

        DynamicColumBean dynamicColumBean5 = new DynamicColumBean();
        dynamicColumBean5.setFiledShowName("油耗量");
        dynamicColumBean5.setFiledCode("fuel_consumption_single");
        dynamicColumBean5.setOrderNum(5);

        DynamicColumBean dynamicColumBean6 = new DynamicColumBean();
        dynamicColumBean6.setFiledShowName("平均油耗量");
        dynamicColumBean6.setFiledCode("fuel_consumption_avg_single");
        dynamicColumBean6.setOrderNum(6);

        DynamicColumBean dynamicColumBean7 = new DynamicColumBean();
        dynamicColumBean7.setFiledShowName("地区");
        dynamicColumBean7.setFiledCode("region_name");
        dynamicColumBean7.setOrderNum(7);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);
        DynamicColumBeanList.add(dynamicColumBean4);
        DynamicColumBeanList.add(dynamicColumBean5);
        DynamicColumBeanList.add(dynamicColumBean6);
        DynamicColumBeanList.add(dynamicColumBean7);

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Date startTime = null;
//        Date endTime = null;
//        try {
//            startTime = sdf.parse(params.get("startDay").toString());
//            endTime = sdf.parse(params.get("endDay").toString());
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        int i = 4;
        // 去除动态列名
//        while (startTime.before(endTime) || startTime.equals(endTime)) {
//            DynamicColumBean dynamicColumBean = new DynamicColumBean();
//            dynamicColumBean.setFiledShowName(sdf.format(startTime));
//            dynamicColumBean.setFiledCode(sdf.format(startTime));
//            dynamicColumBean.setOrderNum(i);
//            i = i++;
//            DynamicColumBeanList.add(dynamicColumBean);
//            Calendar cc = Calendar.getInstance();
//            cc.setTime(startTime);
//            cc.add(cc.DATE, 1);
//            startTime = cc.getTime();
//        }
//        DynamicColumBean dynamicColumBeanAvg = new DynamicColumBean();
//        dynamicColumBeanAvg.setFiledShowName("平均值");
//        dynamicColumBeanAvg.setFiledCode("fuelConsumptionOfDayAvg");
//        dynamicColumBeanAvg.setOrderNum(i);

//        i = i++;
//        DynamicColumBean dynamicColumBeanSimilarAvg = new DynamicColumBean();
//        dynamicColumBeanSimilarAvg.setFiledShowName("同类平均值");
//        dynamicColumBeanSimilarAvg.setFiledCode("fuelConsumptionOfDaySimilarAvg");
//        dynamicColumBeanSimilarAvg.setOrderNum(i);

//        i = i++;
//        DynamicColumBean dynamicColumBeanRegion = new DynamicColumBean();
//        dynamicColumBeanRegion.setFiledShowName("地区");
//        dynamicColumBeanRegion.setFiledCode("region_name");
//        dynamicColumBeanRegion.setOrderNum(7);

//        DynamicColumBeanList.add(dynamicColumBeanAvg);
//        DynamicColumBeanList.add(dynamicColumBeanSimilarAvg);
//        DynamicColumBeanList.add(dynamicColumBeanRegion);
        return DynamicColumBeanList;
    }


    @Override
    public PageInfo carOwnerEngineFuelConsumptionAnalysisOfWeek(Map<String, Object> params) {
        tSSsVehicleModelDao.group_concat_max_len();
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            params.put("car_model_id", item.get("car_model_id"));
            String fuelConsumptionAnalysisOfWeekJson = tSSsVehicleModelDao.getFuelConsumptionAnalysisOfWeek(params);
            item.put("fuelConsumptionAnalysisOfWeekJson", JSON.parseObject(fuelConsumptionAnalysisOfWeekJson, Feature.OrderedField));
            String fuelConsumptionOfWeekAvg = tSSsVehicleModelDao.getFuelConsumptionAvg(params);
            item.put("fuelConsumptionOfWeekAvg", JSON.parseObject(fuelConsumptionOfWeekAvg));
            String fuelConsumptionOfWeekSimilarAvg = tSSsVehicleModelDao.getFuelConsumptionSimilarAvg(params);
            item.put("fuelConsumptionOfWeekSimilarAvg", JSON.parseObject(fuelConsumptionOfWeekSimilarAvg));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineFuelConsumptionAnalysisOfWeek(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineFuelConsumptionAnalysisOfWeek(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("fuelConsumptionAnalysisOfWeekJson") != null) {
                Map<String, Object> fuelConsumptionAnalysisOfWeekJson = (Map<String, Object>) map.get("fuelConsumptionAnalysisOfWeekJson");
                for (String str : fuelConsumptionAnalysisOfWeekJson.keySet()) {
                    if (fuelConsumptionAnalysisOfWeekJson.get(str) != null) {
                        Map<String, Object> detailObject = (Map<String, Object>) fuelConsumptionAnalysisOfWeekJson.get(str);
                        String dayDetail = "平均油耗：" + detailObject.get("fuelConsumption")
                                + "升/时" + "\n"
                                + "工时：" + detailObject.get("fuelConsumptionAvg")
                                + "小时" + "\n"
                                + "耗油量：" + detailObject.get("workHours")
                                + "升";
                        value.put(str, dayDetail);
                    }
                }
            }

            String avgDetailAvg = null;
            if (map.get("fuelConsumptionOfWeekAvg") != null) {
                Map<String, Object> avgDetailObject = (Map<String, Object>) map.get("fuelConsumptionOfWeekAvg");
                String avgDetail = "油耗：" + avgDetailObject.get("fuel_consumption_avg")
                        + "升/时" + "\n"
                        + "总工时：" + avgDetailObject.get("work_hours_total")
                        + "小时" + "\n"
                        + "总耗油量：" + avgDetailObject.get("fuel_consumption_total")
                        + "升";
                value.put("fuelConsumptionOfWeekAvg", avgDetail);
                avgDetailAvg =  avgDetailObject.get("fuel_consumption_avg").toString();
            }

            if (map.get("fuelConsumptionOfWeekSimilarAvg") != null) {
                Map<String, Object> similarAvgDetailObject = (Map<String, Object>) map.get("fuelConsumptionOfWeekSimilarAvg");
                String similarAvgDetail = "油耗：" + similarAvgDetailObject.get("fuel_consumption_avg")
                        + "升/时" + "\n"
                        + "差额：" + String.format("%.2f",(Double.parseDouble(avgDetailAvg != null ? avgDetailAvg : "0") - Double.parseDouble(similarAvgDetailObject.get("fuel_consumption_avg").toString() != null ? similarAvgDetailObject.get("fuel_consumption_avg").toString() : "0")))
                        + "升/时";
                value.put("fuelConsumptionOfWeekSimilarAvg", similarAvgDetail);
            }

            value.put("region_name", map.get("region_name"));
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfFuelAnalysisWeekBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            Calendar cc = Calendar.getInstance();
            cc.setFirstDayOfWeek(Calendar.SUNDAY);
            cc.setMinimalDaysInFirstWeek(4);
            cc.setTime(startTime);
            dynamicColumBean.setFiledShowName(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.WEEK_OF_YEAR) >= 10 ? cc.get(Calendar.WEEK_OF_YEAR) : "0" + cc.get(Calendar.WEEK_OF_YEAR)));
            dynamicColumBean.setFiledCode(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.WEEK_OF_YEAR) >= 10 ? cc.get(Calendar.WEEK_OF_YEAR) : "0" + cc.get(Calendar.WEEK_OF_YEAR)));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            cc.add(cc.WEEK_OF_YEAR, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanAvg = new DynamicColumBean();
        dynamicColumBeanAvg.setFiledShowName("平均值");
        dynamicColumBeanAvg.setFiledCode("fuelConsumptionOfWeekAvg");
        dynamicColumBeanAvg.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanSimilarAvg = new DynamicColumBean();
        dynamicColumBeanSimilarAvg.setFiledShowName("同类平均值");
        dynamicColumBeanSimilarAvg.setFiledCode("fuelConsumptionOfWeekSimilarAvg");
        dynamicColumBeanSimilarAvg.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanRegion = new DynamicColumBean();
        dynamicColumBeanRegion.setFiledShowName("地区");
        dynamicColumBeanRegion.setFiledCode("region_name");
        dynamicColumBeanRegion.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanAvg);
        DynamicColumBeanList.add(dynamicColumBeanSimilarAvg);
        DynamicColumBeanList.add(dynamicColumBeanRegion);
        return DynamicColumBeanList;
    }

    @Override
    public PageInfo carOwnerEngineFuelConsumptionAnalysisOfMonth(Map<String, Object> params) {
        tSSsVehicleModelDao.group_concat_max_len();
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(params.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> thinsList = tSSsVehicleModelDao.getAllThings(params);
        thinsList.forEach(item -> {
            params.put("things_id", item.get("things_id"));
            params.put("car_model_id", item.get("car_model_id"));
            String fuelConsumptionAnalysisOfMonthJson = tSSsVehicleModelDao.getFuelConsumptionAnalysisOfMonth(params);
            item.put("fuelConsumptionAnalysisOfMonthJson", JSON.parseObject(fuelConsumptionAnalysisOfMonthJson, Feature.OrderedField));
            String fuelConsumptionOfMonthAvg = tSSsVehicleModelDao.getFuelConsumptionAvg(params);
            item.put("fuelConsumptionOfMonthAvg", JSON.parseObject(fuelConsumptionOfMonthAvg));
            String fuelConsumptionOfMonthSimilarAvg = tSSsVehicleModelDao.getFuelConsumptionSimilarAvg(params);
            item.put("fuelConsumptionOfMonthSimilarAvg", JSON.parseObject(fuelConsumptionOfMonthSimilarAvg));
        });

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(thinsList);
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> exportCarOwnerEngineFuelConsumptionAnalysisOfMonth(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        PageInfo pageInfo = this.carOwnerEngineFuelConsumptionAnalysisOfMonth(params);
        List<Map<String, Object>> list = new ArrayList<>();
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            Map<String, Object> value = new HashMap<>();
            value.put("advice_name", map.get("advice_name"));
            value.put("model", map.get("model"));
            value.put("things_id", map.get("things_id"));
            if (map.get("fuelConsumptionAnalysisOfMonthJson") != null) {
                Map<String, Object> fuelConsumptionAnalysisOfMonthJson = (Map<String, Object>) map.get("fuelConsumptionAnalysisOfMonthJson");
                for (String str : fuelConsumptionAnalysisOfMonthJson.keySet()) {
                    if (fuelConsumptionAnalysisOfMonthJson.get(str) != null) {
                        Map<String, Object> detailObject = (Map<String, Object>) fuelConsumptionAnalysisOfMonthJson.get(str);
                        String dayDetail = "平均油耗：" + detailObject.get("fuelConsumption")
                                + "升/时" + "\n"
                                + "工时：" + detailObject.get("fuelConsumptionAvg")
                                + "小时" + "\n"
                                + "耗油量：" + detailObject.get("workHours")
                                + "升";
                        value.put(str, dayDetail);
                    }
                }
            }

            String avgDetailAvg = null;
            if (map.get("fuelConsumptionOfMonthAvg") != null) {
                Map<String, Object> avgDetailObject = (Map<String, Object>) map.get("fuelConsumptionOfMonthAvg");
                String avgDetail = "油耗：" + avgDetailObject.get("fuel_consumption_avg")
                        + "升/时" + "\n"
                        + "总工时：" + avgDetailObject.get("work_hours_total")
                        + "小时" + "\n"
                        + "总耗油量：" + avgDetailObject.get("fuel_consumption_total")
                        + "升";
                value.put("fuelConsumptionOfMonthAvg", avgDetail);
                avgDetailAvg =  avgDetailObject.get("fuel_consumption_avg").toString();
            }

            if (map.get("fuelConsumptionOfMonthSimilarAvg") != null) {
                Map<String, Object> similarAvgDetailObject = (Map<String, Object>) map.get("fuelConsumptionOfMonthSimilarAvg");
                String similarAvgDetail = "油耗：" + similarAvgDetailObject.get("fuel_consumption_avg")
                        + "升/时" + "\n"
                        + "差额：" + String.format("%.2f",(Double.parseDouble(avgDetailAvg != null ? avgDetailAvg : "0") - Double.parseDouble(similarAvgDetailObject.get("fuel_consumption_avg").toString() != null ? similarAvgDetailObject.get("fuel_consumption_avg").toString() : "0")))
                        + "升/时";
                value.put("fuelConsumptionOfMonthSimilarAvg", similarAvgDetail);
            }

            value.put("region_name", map.get("region_name"));
            list.add(value);
        });
        return list;
    }

    @Override
    public List<DynamicColumBean> getDynamicColumOfFuelAnalysisMonthBean(Map<String, Object> params) {
        List<DynamicColumBean> DynamicColumBeanList = new ArrayList<>();
        DynamicColumBean dynamicColumBean1 = new DynamicColumBean();
        dynamicColumBean1.setFiledShowName("设备名称");
        dynamicColumBean1.setFiledCode("advice_name");
        dynamicColumBean1.setOrderNum(1);
        DynamicColumBean dynamicColumBean2 = new DynamicColumBean();
        dynamicColumBean2.setFiledShowName("机型");
        dynamicColumBean2.setFiledCode("model");
        dynamicColumBean2.setOrderNum(2);
        DynamicColumBean dynamicColumBean3 = new DynamicColumBean();
        dynamicColumBean3.setFiledShowName("物联网关号");
        dynamicColumBean3.setFiledCode("things_id");
        dynamicColumBean3.setOrderNum(3);

        DynamicColumBeanList.add(dynamicColumBean1);
        DynamicColumBeanList.add(dynamicColumBean2);
        DynamicColumBeanList.add(dynamicColumBean3);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(params.get("startDay").toString());
            endTime = sdf.parse(params.get("endDay").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 4;
        while (startTime.before(endTime) || startTime.equals(endTime)) {
            DynamicColumBean dynamicColumBean = new DynamicColumBean();
            Calendar cc = Calendar.getInstance();
            cc.setFirstDayOfWeek(Calendar.SUNDAY);
            cc.setTime(startTime);
            dynamicColumBean.setFiledShowName(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.MONTH) + 1 >= 10 ? cc.get(Calendar.MONTH) + 1 : "0" + (cc.get(Calendar.MONTH) + 1)));
            dynamicColumBean.setFiledCode(cc.get(Calendar.YEAR) + "-" + (cc.get(Calendar.MONTH) + 1 >= 10 ? cc.get(Calendar.MONTH) + 1 : "0" + (cc.get(Calendar.MONTH) + 1)));
            dynamicColumBean.setOrderNum(i);
            i = i++;
            DynamicColumBeanList.add(dynamicColumBean);
            cc.add(cc.MONTH, 1);
            startTime = cc.getTime();
        }
        DynamicColumBean dynamicColumBeanAvg = new DynamicColumBean();
        dynamicColumBeanAvg.setFiledShowName("平均值");
        dynamicColumBeanAvg.setFiledCode("fuelConsumptionOfMonthAvg");
        dynamicColumBeanAvg.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanSimilarAvg = new DynamicColumBean();
        dynamicColumBeanSimilarAvg.setFiledShowName("同类平均值");
        dynamicColumBeanSimilarAvg.setFiledCode("fuelConsumptionOfMonthSimilarAvg");
        dynamicColumBeanSimilarAvg.setOrderNum(i);

        i = i++;
        DynamicColumBean dynamicColumBeanRegion = new DynamicColumBean();
        dynamicColumBeanRegion.setFiledShowName("地区");
        dynamicColumBeanRegion.setFiledCode("region_name");
        dynamicColumBeanRegion.setOrderNum(i);

        DynamicColumBeanList.add(dynamicColumBeanAvg);
        DynamicColumBeanList.add(dynamicColumBeanSimilarAvg);
        DynamicColumBeanList.add(dynamicColumBeanRegion);
        return DynamicColumBeanList;
    }

    //转换时间为日期
    @Override
    public String conversionDate(double stOrEd, String date) {
        int hours = (int) stOrEd / 60;
        int minutes = (int) stOrEd % 60;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date stOrEdDate = null;
        try {
            stOrEdDate = sdf.parse(date + " " + hours + ":" + minutes);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String dateTime = sdf.format(stOrEdDate);
        return dateTime;
    }


    //导出工时-每日详情-列表功能
    @Override
    public List<CarOwnerEngineTotalHoursDataBean> exportCarOwnerEngineTotalHours(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        List<CarOwnerEngineTotalHoursDataBean> list = new ArrayList<>();
        PageInfo pageInfo = this.carOwnerEngineTotalHours(params);
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            CarOwnerEngineTotalHoursDataBean info = new CarOwnerEngineTotalHoursDataBean();
            info.setAdvice_name(map.get("advice_name").toString());
            info.setModel(map.get("model") == null ? "" : map.get("model").toString());
            info.setThings_id(map.get("things_id").toString());
            if (map.get("workHoursJson") != null) {
                Map<String, Object> workHoursJson = (Map<String, Object>) map.get("workHoursJson");
                List startTimeList = (List) workHoursJson.get("startTimeList");
                List endTimeList = (List) workHoursJson.get("endTimeList");
                Double workHoursSum1 = Double.parseDouble(workHoursJson.get("workHours").toString()) ;
                int hour = (int) (workHoursSum1 % 24);
                int minutes = (int) (workHoursSum1 % 1 * 60);
                String workHoursSum1ToTime = hour + "小时" + minutes + "分钟"
                        + "\n"
                        + workHoursSum1 + "h";
                String workHours = workHoursJson.get("workHours").toString();
                String availability = String.format("%.2f", Double.parseDouble(workHours) / 8 * 100) + "%";
                double st = Double.parseDouble((String) startTimeList.get(0)) * 60;
                double ed = Double.parseDouble((String) endTimeList.get(endTimeList.size() - 1)) * 60;

                //转换时间（数据如7.0166667 和 2022-04-11 -> 2022-04-11 07：00）
                String startTime = this.conversionDate(st, params.get("date").toString());
                String endTime = this.conversionDate(ed, params.get("date").toString());

                info.setWorkHours(workHoursSum1ToTime);
                info.setAvailability(availability);
                info.setStartTime(startTime);
                info.setEndTime(endTime);
            } else {
                info.setStartTime("/");
                info.setEndTime("/");
                info.setWorkHours("/");
                info.setAvailability("/");
            }
            info.setRegionName(map.get("region_name") == null ? "/" : map.get("region_name").toString());
            list.add(info);
        });

        return list;
    }

    //导出工时-时间区间-列表功能
    @Override
    public List<CarOwnerEngineTotalHoursDataBeanNew> exportCarOwnerEngineTotalHoursNew(Map<String, Object> params) {
        params.put("pageSize", 99999);
        params.put("currentPage", 1);

        List<CarOwnerEngineTotalHoursDataBeanNew> list = new ArrayList<>();
        // 获取数据，这里修改了开始时间和结束时间
        PageInfo pageInfo = this.carOwnerEngineTotalHoursBetweenDay(params);
        pageInfo.getList().forEach(item -> {
            Map<String, Object> map = (Map<String, Object>) item;
            CarOwnerEngineTotalHoursDataBeanNew info = new CarOwnerEngineTotalHoursDataBeanNew();
            info.setAdviceName(map.get("advice_name").toString());
            info.setModel(map.get("model") == null ? "" : map.get("model").toString());
            info.setUserName(map.get("user_name") == null ? "" : map.get("user_name").toString());
//            info.setThings_id(map.get("things_id").toString());
            if (map.get("workHoursJson") != null) {
                Map<String, Object> workHoursJson = (Map<String, Object>) map.get("workHoursJson");
//                List startTimeList = (List) workHoursJson.get("startTimeList");
//                List endTimeList = (List) workHoursJson.get("endTimeList");
//                Double workHoursSum1 = Double.parseDouble(workHoursJson.get("workHours").toString()) ;
                Double workHoursSum = 0.0 ;
                int mapSize = 0;
                for (Map.Entry<String,Object> entry:workHoursJson.entrySet()){
                    Double value = Double.parseDouble(entry.getValue().toString());
                    workHoursSum += value;
                    mapSize++;
                }

//                int hour = (int) (workHoursSum1 % 24);
//                int minutes = (int) (workHoursSum1 % 1 * 60);
//                String workHoursSum1ToTime = hour + "小时" + minutes + "分钟"
//                        + "\n"
//                        + workHoursSum1 + "h";
//                Double workHours = workHoursSum/mapSize;
                // 开工率=时间段内，开机天数/总天数
                // 总天数
                int totalDays = FunUtil.betweenDaysCount(params.get("startDay").toString(),params.get("endDay").toString());

                // 开机天数
                Double workDayCount =  Double.parseDouble(map.get("workDayCount").toString());
                Double availability = workDayCount/(totalDays+1);

//                String availability = String.format("%.2f", workHours / 8 * 100) + "%";
                String availabilityString = String.format("%.2f", availability * 100) + "%";
//                String availability = "0";
//                double st = Double.parseDouble((String) startTimeList.get(0)) * 60;
//                double ed = Double.parseDouble((String) endTimeList.get(endTimeList.size() - 1)) * 60;

                String startTime =  params.get("startDay").toString();
                String endTime = params.get("endDay").toString();

                info.setWorkHours(workHoursSum.toString());
                info.setAvailability(availabilityString);
//                info.setStartTime(startTime);
//                info.setEndTime(endTime);
            } else {
//                info.setStartTime("/");
//                info.setEndTime("/");
                info.setWorkHours("/");
                info.setAvailability("/");
            }
            info.setRegionName(map.get("region_name") == null ? "/" : map.get("region_name").toString());
            list.add(info);
        });

        return list;
    }


    //导出设备油耗-时间区间-列表功能
//    @Override
//    public List<CarOwnerEngineFuelConsumptionDataBean> exportCarOwnerEngineFuelConsumptionAnalysisNew(Map<String, Object> params) {
//        params.put("pageSize", 99999);
//        params.put("currentPage", 1);
//
//        List<CarOwnerEngineTotalHoursDataBean> list = new ArrayList<>();
//        // 获取数据，这里修改了开始时间和结束时间
//        PageInfo pageInfo = this.carOwnerEngineTotalHoursBetweenDay(params);
//        pageInfo.getList().forEach(item -> {
//            Map<String, Object> map = (Map<String, Object>) item;
//            CarOwnerEngineTotalHoursDataBean info = new CarOwnerEngineTotalHoursDataBean();
//            info.setAdvice_name(map.get("advice_name").toString());
//            info.setModel(map.get("model") == null ? "" : map.get("model").toString());
//            info.setThings_id(map.get("things_id").toString());
//            if (map.get("workHoursJson") != null) {
//                Map<String, Object> workHoursJson = (Map<String, Object>) map.get("workHoursJson");
////                List startTimeList = (List) workHoursJson.get("startTimeList");
////                List endTimeList = (List) workHoursJson.get("endTimeList");
////                Double workHoursSum1 = Double.parseDouble(workHoursJson.get("workHours").toString()) ;
//                Double workHoursSum = 0.0 ;
//                int mapSize = 0;
//                for (Map.Entry<String,Object> entry:workHoursJson.entrySet()){
//                    Double value = Double.parseDouble(entry.getValue().toString());
//                    workHoursSum += value;
//                    mapSize++;
//                }
//
////                int hour = (int) (workHoursSum1 % 24);
////                int minutes = (int) (workHoursSum1 % 1 * 60);
////                String workHoursSum1ToTime = hour + "小时" + minutes + "分钟"
////                        + "\n"
////                        + workHoursSum1 + "h";
////                Double workHours = workHoursSum/mapSize;
//                // 开工率=时间段内，开机天数/总天数
//                // 总天数
//                SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd ");
//
//                Date date1 = null;
//                try {
//                    date1 = formatter.parse(params.get("startDay").toString());
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                Date date2 = null;
//                try {
//                    date2 = formatter.parse(params.get("endDay").toString());
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//
//                int totalDays = FunUtil.betweenDaysCount(date1,date2);
//                // 开机天数
//                Double workDayCount =  Double.parseDouble(map.get("workDayCount").toString());
//                Double availability = totalDays/workDayCount;
//
////                String availability = String.format("%.2f", workHours / 8 * 100) + "%";
//                String availabilityString = String.format("%.2f", availability / 100) + "%";
////                String availability = "0";
////                double st = Double.parseDouble((String) startTimeList.get(0)) * 60;
////                double ed = Double.parseDouble((String) endTimeList.get(endTimeList.size() - 1)) * 60;
//
//                String startTime =  params.get("startDay").toString();
//                String endTime = params.get("endDay").toString();
//
//                info.setWorkHours(workHoursSum.toString());
//                info.setAvailability(availabilityString);
//                info.setStartTime(startTime);
//                info.setEndTime(endTime);
//            } else {
//                info.setStartTime("/");
//                info.setEndTime("/");
//                info.setWorkHours("/");
//                info.setAvailability("/");
//            }
//            info.setRegionName(map.get("region_name") == null ? "/" : map.get("region_name").toString());
//            list.add(info);
//        });
//
//        return list;
//    }

    @Override
    public PageInfo equipmentReportByDay(Map<String, Object> paramsMap) {
        Integer pageSize = Integer.valueOf(paramsMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(paramsMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> list = tSSsVehicleModelDao.equipmentReportByDay(paramsMap);
        PageInfo pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}
